Problem Description
A murder happened in the hotel. As the best detective in the town, you should examine all the N rooms of the hotel immediately. However, all the doors of the rooms are locked, and the keys are just locked in the rooms, what a trap! You know that there is exactly one key in each room, and all the possible distributions are of equal possibility. For example, if N = 3, there are 6 possible distributions, the possibility of each is 1/6. For convenience, we number the rooms from 1 to N, and the key for Room 1 is numbered Key 1, the key for Room 2 is Key 2, etc.
To examine all the rooms, you have to destroy some doors by force. But you don’t want to destroy too many, so you take the following strategy: At first, you have no keys in hand, so you randomly destroy a locked door, get into the room, examine it and fetch the key in it. Then maybe you can open another room with the new key, examine it and get the second key. Repeat this until you can’t open any new rooms. If there are still rooms un-examined, you have to randomly pick another unopened door to destroy by force, then repeat the procedure above, until all the rooms are examined. Now you are only allowed to destroy at most K doors by force. What’s more, there lives a Very Important Person in Room 1. You are not allowed to destroy the doors of Room 1, that is, the only way to examine Room 1 is opening it with the corresponding key. You want to know what is the possibility of that you can examine all the rooms finally. |
Input
The first line of the input contains an integer T (T ≤ 200), indicating the number of test cases. Then T cases follow. Each case contains a line with two numbers N and K. (1 < N ≤ 20, 1 ≤ K < N)
|
Output
Output one line for each case, indicating the corresponding possibility. Four digits after decimal point are preserved by rounding.
|
Sample Input
3 3 1 3 2 4 2 |
Sample Output
0.3333 0.6667 0.6250 |
如果用s[n][k]表示n个门中有k个环的情况数,则有:
s[n][k] = s[n - 1][k - 1] + (n - 1) * s[n - 1][k], 1 <= k <= n - 1
上面的公式可以这样理解:当前n - 1个门组成k - 1个环的时候,再加入第n个门形成一个单环即可;当n - 1个门组成k个环时,要加入第n个门,为了不增加环的个数,只需要将n插在前n - 1个门的任意一个门之后即可。
初始化情况为:
s[i][0] = 0;
s[i][i] = 1, i >= 1
因为第一个门不能在环中,只需将第一个门在环中的情况减去,即是s[i][j] - s[i - 1][j - 1]才是合法的情况。
#include<stdio.h>
#include<string.h>
__int64 p[21][21];
__int64 q[21];
int main()
{
int T;
double sum;
int n,k;
int i,j;
p[1][1]=1;
q[0]=q[1]=1;
for(i=2;i<21;i++)
{
for(j=1;j<=i;j++)
{
p[i][j]=p[i-1][j-1]+p[i-1][j]*(i-1);
}
q[i]=q[i-1]*i;
}
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&k);
sum=0;
for(i=1;i<=k;i++)
{
sum+=p[n][i]*1.0-p[n-1][i-1];
}
printf("%.4lf\n",sum/q[n]);
}
return 0;
}