问题
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.
回答1:
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.
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'
回答2:
Are you trying to do something like this:
void main(void) {
int x[] = {3, 5, 7, 10}
int y[] = {5, 9, 12, 23}
int i=0, j=0;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
if (x[i]<10 && y[j]<5)
{
if(x[i]+y[j]==p)
{
//do something
}
}
}
}
}
回答3:
The fastest algorithm I know will be :
- Let
m
be the maximum of your constraints, andz
the items constrained bym
. In your casem = 10, z = x
. This is because as m grows, p - m decreases. - I assume your items are generic. Create a map and associate the key
p - z[i].value()
toz[i]
- Take each item
obj
in the other list (in your casey
), and look ifobj.value()
is a key of your map. If it is, save bothobj.value()
andmap[obj.value()]
Using the property of retrieving in a map in constant time O(1)
, you have an algorithm which run in O(sizeof(x)+sizeof(y))
来源:https://stackoverflow.com/questions/9373450/choose-k-items-from-a-set-of-x-and-y-to-meet-certain-criteria