views:

70

answers:

2

I need to do some task. There are numbers give in two rows and they act like pairs of integers (a, b). I have to find the maximum 5 numbers of the a-row and then select the max of those 5 but this time from the b-row. Ex:

1 4
5 2
3 3
7 5
6 6
2 9
3 1

In this example, the pair i need is (6,6) because 6 (a) is in the top 5 of the a[i] numbers and 6 (b) is the maximum in the b section of those 5 pairs. I was thinking of doing this with vectors and my own defined structures, also use some temp arrays but i don't know if that's the right thing to do maybe there is simpler way to do this.

Any ideas ?

EDIT: I also need the index number of the pair (in the case that is 5, it's the fifth pair i.e).

+2  A: 

A priority queue holding pairs that does its order evaluations based on the first element of the pair would be appropriate. You could insert all the pairs and then extract the top 5. Then just iterate on that list of pairs looking for the max of the second element of each pair.

edit

I should say that it is a decent solution only if you can accept a runtime on the order of O(n * lg n)

David Gladfelter
Since he also needs the index, the priority queue should actually hold triples (first element, second element, index).
Vanessa MacDougal
oh yeah, good point.
David Gladfelter
A: 

Alternate approaches:

Push triples (first, second, index) into a vector and then std::partial_sort the first 5 items using a descending order functor on the first element. Then use std::max_element with a second functor to find the max of the second element, and grab its index. If I'm reading the complexity of partial_sort correctly this should run in linear time (O(n)) because we're always sorting a max of 5 elements rather than O(n*log n).

Similarly, have the vector only contain pairs and sort a second vector containing indexes into the first one.

Mark B
I thought of this type of solution, but rereading the question it seems as if you want to order the second column for all elements whose first column has one of the highest 5 values. That means that there can be repeated element (the example does have repeated first column values), and as such you do not know for a fact how many elements you want to 'partially' sort. Of course, for a O( N log N ) solution you can just use `std::sort` on the whole vector.
David Rodríguez - dribeas
Amending my solution then, all you have to do is make the predicate sort by first element descending and second element descending when first element equal. This way ties on the first element are resolved giving you the max of the second element that go with the corresponding first element. This should still be linear time.
Mark B
(1, 100), (1, 101), (1, 102), (1,103), (1, 104), (2, 1) will remove (1,100) from the vector, and use (2,1) as part of the solution, when ordering by the second element (limited to the biggest 5 first elements) should include all (1,x) pairs
David Rodríguez - dribeas