从一组x和y的选择k个项目,以满足某些标准标准、项目、以满足

由网友(い花落ぬ微凉づ)分享简介:我已经给了 X 和是的项目,我需要选择一些 X 有的是有一定的约束说 X&LT; 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 an...

我已经给了 X 的项目,我需要选择一些 X 有的有一定的约束说 X&LT; 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'
阅读全文

相关推荐

最新文章