Cutting rope
Time Limit: 1 Sec Memory Limit: 128 MBSubmissions: 3 Solved: 3
Description
Inside a rope of length n, n-1 points are placed with distance 1 from each other and from the endpoints. Among these points, we choose m-1 points at random and cut the rope at these points to create m segments.
Let E(n, m) be the expected length of the shortest segment. Give n and m, find E(n, m).
Give your answer rounded to 5 decimal places behind the decimal point.
Input
The first line of input will be a positive integer T indicating how many data sets will be included. Each of the next T lines will contain two integers n, m (1 ≤ n, m ≤ 100000; m ≤ n) as mentioned before.
Output
For each test case, output E(n, m) rounded to 5 decimal places behind the decimal point in separate line.
Sample Input
3 2 2 4 2 100 10
Sample Output
1.00000 1.33333 1.52740
HINT
Source
The 8th(2013) ACM Programming Contest of HUST
这个题目是个简单的组合数学。
题意是这样的:将长度为N的rope切成M块,然后取最小块长度的期望。
这个题目的做法是:枚举最小长度,最小长度范围是[1,n/m] ,对于每一种最小长度,先把最基本的构成最小长度的块数拿出来,构成M个最小堆,然后其他的块拿出来分配到各个堆里去。貌似这里会出现一个问题,就是如果剩下的随机分配了可能导致最小长度变大了。这个问题很好,下面我们这样解决。
我们用C(i) 代表最小长度大于等于i的概率,用A(I)代表最小长度为i的概率,于是我们得到
A(i)=C(i)-C(i+1)
A(N/M)=C(N/M)
于是我们得到E(n,m)=A(1)+2*A(2)+......+N/M*A(N/M)=C(1)+C(2)+......+C(N/M)。
其中这里的C(i)=C(n-i*m+m-1,m-1)/C(n-1,m-1) (这里使用隔板法)。
于是代码就很容易得到了。
两层循环即可。
注意这里的复杂度是O(N/M*M)=O(N)。
下面是代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int i,j,T,n,m;
double ans,tt;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for (i=1,ans=0;i<=n/m;i++){
for (j=1,tt=1;j<=m-1;j++){
tt*=(n-i*m+m-j)*1.0/(n-j);
}
ans+=tt;
}
printf("%.5f\n",ans);
}
return 0;
}