A | B | magic(A,B) |
(1,2) | (1,2) | 3 |
(1,2) | (2,1) | 4 |
(2,1) | (1,2) | 4 |
(2,1) | (2,1) | 3 |
So the answer is 2. Here are the other topcoder examples:
# N K Return Value - -- -- ----------------------- 0 1 1 1 1 2 1 4 2 3 8 18 3 10 47 13168189440000
Fortunately, we don't have to enumerate all A and B. Let's instead just use A = { 1, 2, ..., N }, and enumerate all possible B. Suppose the number of (A,B) pairs where magic(A,B) ≥ K is equal to X. Then, I will contend that if we consider A to be any permutation of the numbers from one to N and enumerate all possible B, then the number of (A,B) pairs where magic(A,B) ≥ K will also equal X.
Let's illustrate this with an example. Suppose N is 3 and K is 8. This is example 3. Then, let's consider A = { 1, 2, 3 } and all possible B:
A B magic(A,B) >= 8? (1,2,3) (1,2,3) 6 No (1,2,3) (1,3,2) 7 No (1,2,3) (2,1,3) 7 No (1,2,3) (2,3,1) 8 Yes (1,2,3) (3,1,2) 8 Yes (1,2,3) (3,2,1) 8 YesSo, X is 3. I contend that for any single setting of A, if you look at all potential B, the number of B's for which magic(A,B) ≥ 8 is three. The reason is that there will be a one-to-correspondence betwen magic({1,2,3},B) and magic(A,B). Let me continue the example. Suppose we set A to be { 2, 1, 3 }. Then:
magic({2,1,3},{1,2,3}) is equivalent to magic({1,2,3},{2,1,3}) = 7. magic({2,1,3},{1,3,2}) is equivalent to magic({1,2,3},{3,1,2}) = 8. magic({2,1,3},{2,1,3}) is equivalent to magic({1,2,3},{1,2,3}) = 6. magic({2,1,3},{2,3,1}) is equivalent to magic({1,2,3},{3,2,1}) = 8. magic({2,1,3},{3,1,2}) is equivalent to magic({1,2,3},{1,3,2}) = 7. magic({2,1,3},{3,2,1}) is equivalent to magic({1,2,3},{2,3,1}) = 8.As you can see, the number (A,B) pairs such that magic(A,B) ≥ 8 is as before: 3.
What's the upshot of this? It's that you can calculate X for A = { 1, 2, 3, ..., N }, and all possible B, and that will take N! iterations. Then, you simply multiply X by (N!), because X will be the same for every permutation of A, and there are (N!) permutations.
You should program this up, and use next_permutation() from the C++ algorithms library to generate all of the permutations.