TopCoder problem "KeysInBoxes" used in SRM 391 (Division I Level Two)



Problem Statement

    

There are N boxes numbered from 1 to N and N keys numbered from 1 to N. The i-th key can only be used to open the i-th box. Now, we randomly put exactly one key into each of the boxes. We assume that all configurations of keys in boxes occur with the same probability. Then we lock all the boxes. You have M bombs, each of which can be used to open one locked box. Once you open a locked box, you can get the key in it and perhaps open another locked box with that key. Your strategy is to select a box, open it with a bomb, take the key and open all the boxes you can and then repeat with another bomb.

Return the probability that you can get all the keys. The return value must be a string formatted as "A/B" (quotes for clarity), representing the probability as a fraction. A and B must both be positive integers with no leading zeroes, and the greatest common divisor of A and B must be 1.

 

Definition

    
Class:KeysInBoxes
Method:getAllKeys
Parameters:int, int
Returns:String
Method signature:String getAllKeys(int N, int M)
(be sure your method is public)
    
 

Constraints

-N will be between 1 and 20, inclusive.
-M will be between 1 and N, inclusive.
 

Examples

0)
    
2
1
Returns: "1/2"
When box 1 contains key 2, you can get all the keys.
1)
    
2
2
Returns: "1/1"
When N=M, you can always get all the keys.
2)
    
3
1
Returns: "1/3"
There are 6 possible configurations of keys in boxes. Using 1 bomb, you can open all the boxes in 2 of them:
  • box 1 - key 2, box 2 - key 3, box 3 - key 1;
  • box 1 - key 3, box 2 - key 1, box 3 - key 2.
3)
    
3
2
Returns: "5/6"
Now, when you have 2 bombs, you are only unable to get all the keys in the following configuration: box 1 - key 1, box 2 - key 2, box 3 - key 3.
4)
    
4
2
Returns: "17/24"

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8202

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=11125&pm=8202

Writer:

stone

Testers:

PabloGilberto , Olexiy , lovro , ivan_metelsky

Problem categories:

Simple Math