Here’s a jolly and simple game: line up a row ofNidentical coins, all with the heads facingdown onto the table and the tails upwards, and for exactlyKtimes take one of the coins, toss itinto the air, and replace it as it lands either heads-up or heads-down. You may keep all of thecoins that are face-up by the end.
Being, as we established last year, a ruthless capitalist, you have resolved to play optimally towin as many coins as you can. Across all possible combinations of strategies and results, whatis the maximum expected (mean average) amount you can win by playing optimally?
Input
One line containing two space-separated integers:
–N(1≤N≤400), the number of coins at your mercy;
–K(1≤K≤400), the number of flips you must perform.
Output
Output the expected number of heads you could have at the end, as a real number. The outputmust be accurate to an absolute or relative error of at most 10-6.
Examples
Sample Input 1
2 1
Sample Output 1
0.5
Sample Input 2
2 2
Sample Output 2
1
Sample Input 3
2 3
Sample Output 3
1.25
Sample Input 4
6 10
Sample Output 4
4.63476563
Sample Input 5
6 300
Sample Output 5
5.5
刚开始这题不知道什么意思,样例看不懂,第二天手推样例懂了,递推也是一样的思路。
根据翻了i次以后每个状态(j个向上)及这个状态的概率,再翻一次的操作就是随便选一个向下的硬币翻,于是1/2概率变成j个向上,1/2概率变成j+1个向上。如果原来n个硬币都向上了,那么再翻一次是n或者n-1。
设f(i,j):n个硬币翻了i次以后向上有j个的概率
1/2*f(i,j)-> f(i+1,j+1),1/2*f(i,j)->f(i+1,j) ,j<n
1/2*f(i,j)-> f(i+1,j-1),1/2*f(i,j)->f(i+1,j) ,j=n
#include<bits/stdc++.h>
using namespace std;
int n,k;
double p[500][500]; //n个硬币翻了i次以后向上有j个的概率
int main()
{
cin>>n>>k;
p[0][0]=1;
for(int i=0;i<k;i++)
{
for(int j=0;j<n;j++)p[i+1][j]+=p[i][j]/2,p[i+1][j+1]+=p[i][j]/2;
p[i+1][n]+=p[i][n]/2;
p[i+1][n-1]+=p[i][n]/2;
}
double ans=0;
for(int j=1;j<=n;j++)ans+=j*p[k][j];
printf("%.8f\n",ans);
return 0;
}