Description
ICPC (International Cardboard Producing Company) is in the business of producing cardboard boxes. Recently the company organized a contest for kids for the best design of a cardboard box and selected M winners. There are N prizes for the winners, each one carefully packed in a cardboard box (made by the ICPC, of course). The awarding process will be as follows:
- All the boxes with prizes will be stored in a separate room.
- The winners will enter the room, one at a time.
- Each winner selects one of the boxes.
- The selected box is opened by a representative of the organizing committee.
- If the box contains a prize, the winner takes it.
- If the box is empty (because the same box has already been selected by one or more previous winners), the winner will instead get a certificate printed on a sheet of excellent cardboard (made by ICPC, of course).
- Whether there is a prize or not, the box is re-sealed and returned to the room.
Input
The first and only line of the input file contains the values of
N and
M (
).
Output
The first and only line of the output file should contain a single real number: the expected number of prizes given out. The answer is accepted as correct if either the absolute or the relative error is less than or equal to 10
-9.
Sample Input
sample input | sample output |
5 7 | 3.951424 |
sample input | sample output |
4 3 | 2.3125 |
解题思路1:其实第一次看到这道题的时候没有理解它的意思,就拿起笔算了一下,结果发现样例一的结果等于以4 / 5为公比的等比数列的前7项和,样例二的结果等于以3 / 4
为公比的等比数列前3项和,所以就想到结果是否等于以(N - 1) / N为公比的等比数列的前M项和,于是就交了代码,然后就水过去了。。。
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int n,m;
while(scanf("%d %d",&n,&m) != EOF){
double ans = 0;
double temp = (double)(n - 1) / n;
for(int i = 0;i < m;i++){
ans += pow(temp,i);
}
printf("%.9f\n",ans);
}
return 0;
}
解题思路2:好吧,其实这是一道概率DP题。定义dp[i]为第i个人得到奖品的概率,则1 - dp[i]为第i个人得不到奖品的概率。很明显,dp[1] = 1,即第一个人无论怎么选都能拿到奖品。对于dp[i]来说,他能否获奖与dp[i - 1]的选择有关。如果i - 1没有得奖,那么i得奖的概率与i - 1得奖的概率相同;如果i - 1得到奖品,那么i得奖的概率等于i - 1得奖的概率减去 1 / n,即dp[i] = (1 - dp[i - 1]) * dp[i - 1] + dp[i - 1] * (dp[ i - 1] - 1.0 / n),化简得dp[i] = (1 - 1.0 / n) * dp[i - 1]。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 100005;
double dp[maxn];
int main()
{
int n,m;
while(scanf("%d %d",&n,&m) != EOF){
memset(dp,0,sizeof(dp));
dp[1] = 1;
double ans = 1;
for(int i = 2;i <= m;i++){
dp[i] = (1 - 1.0 / n) * dp[i - 1];
ans += dp[i];
}
printf("%.9f\n",ans);
}
return 0;
}