题目描述
BuggyD loves to carry his favorite die around. Perhaps you wonder why it's his favorite? Well, his die is magical and can be transformed into an N-sided unbiased die with the push of a button. Now BuggyD wants to learn more about his die, so he raises a question:
What is the expected number of throws of his die while it has N sides so that each number is rolled at least once?
输入格式
The first line of the input contains an integer t, the number of test cases. t test cases follow.
Each test case consists of a single line containing a single integer N (1 <= N <= 1000) - the number of sides on BuggyD's die.
输出格式
For each test case, print one line containing the expected number of times BuggyD needs to throw his N-sided die so that each number appears at least once. The expected number must be accurate to 2 decimal digits.
题意翻译
一个n面的骰子,求期望掷几次能使得每一面都被掷到。
输入输出格式
输入格式
2 1 12
输出格式
1.00 37.24
思路
令\(dp_i\)为表示当前已经得到了 ii 个面后的期望次数。那么我们会有\(2\)种情况
\(1:\)掷出已经出现过的面,概率为\(\frac{i}{n}\)
\(2:\)掷出没有出现过的面,概率为\(\frac{n-i}{n}\)
则有:
\(dp_i=\frac{i}{n}dp_i+\frac{n-i}{n}dp_{i+1}+1\)
\(\frac{n-i}{n}dp_i=\frac{n-i}{n}dp_{i+1}+1\)
\(dp_i=dp_{i+1}+\frac{n}{n-i}\)
边界条件为\(dp_n=0\),倒推即可求出答案。
代码
/************************************************ *Author : xzj213 *Created Time : 2020.01.30.17:44 *Mail : xzj213@qq.com *Problem : SP1026 ************************************************/ #include <bits/stdc++.h> #define REP(i,a,b) for(register int i=(a);i<=(b);i++) #define DREP(i,a,b) for(register int i=(a);i>=(b);i--) #define mem(a,x) memset((a),(x),sizeof(a)) #define pii pair<int,int> #define lson k<<1 #define rson k<<1|1 #define x first #define y second #define str(a) strlen(a) using namespace std; const int maxn=1000+5; int n,T; double dp[maxn]; void chkmax(int &a,int b){if(a<b)a=b;} void chkmin(int &a,int b){if(a>b)a=b;} int read() { int x=0,f=1; char ch=getchar(); while(ch>57 || ch<48){if(ch==45)f=-1;ch=getchar();} while(ch<=57 && ch>=48){x=x*10+ch-48;ch=getchar();} return x*f; } int main() { freopen("SP1026.in","r",stdin); freopen("SP1026.out","w",stdout); T=read(); while(T--) { n=read(); dp[n]=0; DREP (i,n-1,0) dp[i]=dp[i+1]+1.0*n/(n-i); printf("%.2lf\n",dp[0]); } return 0; }
来源:https://www.cnblogs.com/xzj213/p/12243283.html