从一组x和y的选择k个项目,以满足某些标准 [英] choose k items from a set of x and y to meet certain criteria

查看:104
本文介绍了从一组x和y的选择k个项目,以满足某些标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经给了 X 的项目,我需要选择一些 X 有的有一定的约束说 X< 10 和 Y'LT; 5 和总数应 P

I have given x and y items , I need to choose some x and some y with some constrain say x < 10 and y < 5 and the total number should be p.

如何解决这样的问题。算法/数学技术。

How to solve such problem. Algorithm/ mathematical technique.

推荐答案

诀窍是,我们只需要通过一个阵列(如x_array),我们可以计算出Ÿ使用PX = Y。现在,我们只需要保证y是y_array,我们知道我们有我们的答案。为了确保y是y_array,我们做了一组或二叉搜索树进行快速查找。

The trick is we only need to go through one array (e.g. the x_array), and we can work out y using p-x=y. Now we only need to ensure y is in the y_array and we know we have our answer. To ensure y is in the y_array, we make a set or binary search tree for fast look-ups.

下面是一些Python code:

Here is some python code:

p=13
xs=[1,3,99,9,18]
ys=[10,4,33]

y_set=set(ys)

#y=p-x
results=((x,p-x) for x in xs if x<10 and p-x<5 and p-x in y_set)

print "x=%s,y=%s,p=13" % results.next()
'x=9,y=4,p=13'

这篇关于从一组x和y的选择k个项目,以满足某些标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆