Hints for SRM 635, D1, 500-pointer (StoryFromTCO)

James S. Plank

Sun Oct 26 13:20:28 EDT 2014
Problem Statement.
As with a lot of topcoder problems, this one's solution is pretty easy, once you figure out how to think about it.

When you start, each element of places and cutoff may be partitioned into two sets: G for "Good" and B for "Bad". It's pretty obvious what they are. If you can solve the problem, you have swap every element of B, so you can order the places and cutoff elements that are in B in any order you want.

What order gives you the greatest likelihood of success? I'd say sorting those elements of places and cutoff (I used a multiset for each). Now, start with the lowest element of each multiset. If the places element is ≤ the cutoff element, then we're good. In fact, at that point, you can remove it from B (i.e. remove the elements from the multiset). (Also, don't put it back in G; just record that you removed it).

Suppose we've removed some of these elements of B, and now the elements with the smallest place and cutoff don't work -- the place is greater than the cutoff. Let's call those values p and c. Since the remaining elements in B have higher place values, you need to get an element from G. Which one should you get? Well, its place value should be ≤ c; otherwise it's useless to swap it in. And its cutoff value should be as high as possible, because you want to maximize your chances of one of the other elements of B substituting for it.

So you find that element, and put it into B, by inserting its place and cutoff into the two multisets. Keep doing that until you're done, and B is empty, or until you can't find a replacement, in which case you return -1.

Let's take example 4: places is {14,11,42,9,19} and cutoff is {11,16,37,41,47}. We'll start with G = { (11.16), (9,41), (19,47) } and B = { (14,11), (42,37) }. Our multisets are (14,42) for places and (11,37) cutoffs. The first element won't work, so we add (9,41) to B.

Now the multisets are (9,14,42) for places and (11,37,41) cutoffs. We can remove the first two elements of B, and now the multisets are (42) for places and (41) cutoffs. We add (19,47), and you should see that now we can remove everything from B.

B's initial size was 2, and we added 2 elements from G to it, so the total number of permutations required is 4.

Back of the envelope running time is O(n2log(n)), because there's no good way to avoid a linear search when you're searching for the best element from G.