Hints for SRM 592, D2, 500-Pointer (LittleElephantAndPermutationDiv2)

James S. Plank

Sat Sep 28 12:20:52 EDT 2013
Problem Statement.
As always, the first thing that you should do is look at the constraints, and then figure out if dumb strategies will work. The maximum value of N is 10, so there are 10! permutations. What is that? 3,628,800.

Clearly, you cannot generate all permutations of A and B, because that will be roughly 9 * 1012. With topcoder, you get on the order of 107 operations before you time out.

Think about it though, with an example, like Example 3, where N equals 3 and K equals 8. Let's run through the permutations of A, and what the possibilities for B are:

A = (1,2,3).  B = (2,3,1) or (3,1,2) or (3,2,1)
A = (1,3,2).  B = (2,1,3) or (3,2,1) or (3,1,2)
A = (2,1,3).  B = (3,2,1) or (1,3,2) or (2,3,1)
A = (2,3,1).  B = (3,1,2) or (1,2,3) or (2,1,3)
A = (3,1,2).  B = (1,2,3) or (2,3,1) or (1,3,2)
A = (3,2,1).  B = (1,3,2) or (2,1,3) or (1,2,3)
Hmmm. There are three B's for each A. Will that always be true? Well, think about it. Start with A = (1,2,3), and we have three B's. Let's call them B0 = (2,3,1), B1 = (3,1,2) and B2 = (3,2,1).

Now, let's permute A, so that it equals (2,1,3). We did that by swapping the first two digits. If we swap the first two digits of the B's, we'll get the answers for (2,1,3): B0 becomes (3,2,1), B1 becomes (1,3,2) and B2 = (2,3,1).

So, this means that the number of B's for all permutations of A is the same. That's nice, because now we can simply pick one permutation of A, calculate the number of B's through enumeration, and multiply it by the number of possible permutations of A (which is N!).

So, what I did was set A = (1, 2, 3, ..., N), and generate the N! permutations of B, either using next_permutation() from the C++ Algorithm library, or using recursion as described in class, and simply counted the permutations that have magic(A, B)K. I multiplied that result by N!, compiled, tested and submitted.

In reality, before doing that, I generated 10! permutations using next_permutation() and timed it, to be sure that it would be fast enough. It took something like 0.3 seconds on topcoder's server. That seemed fast enough to me, so I did the solution outlined above, and it worked.

Give it a try!