spoj Favorite Dice (probability dp + expectation)

Title:

Roll an n-sided die and ask how many times you expect each side to be rolled.

answer:

Probability dp is always pushed backwards.
We set dp[x] to indicate the number of times
that it has been shaken to x faces, and then dp[n] = 0 (that is, not shaken once)
dp[0] is the answer
to dp [i], we consider that i faces have already been shaken, and dynamic planning needs to consider the state. The last state may have been shaken to i faces (that is, the face that was shaken this time has already appeared), or it may have been shaken to i- 1 face (that is, the face that was shaken this time appears for the first time)
(1) The expectation obtained by throwing to the face that has been thrown is i/n *dp[i]
(2) The expectation of throwing to the face that has not been thrown It is (ni)/n *dp[i+1]
so the recurrence formula is:
dp[i] = i/n *dp[i]+(ni)/n *dp[i+1] +1.
Both sides Is dp[i] simplified:
dp[i]=dp[i+1]+n/(ni)

Code:

#include<bits/stdc++.h>
using namespace std;
double dp[1010];
int n;
int main()
{
    
    
    int t;
    scanf("%d",&t);
    while(t--){
    
    
        scanf("%d",&n);
        met(dp,0.0);
        for(int i=n-1;i>=0;i--)
            dp[i]=dp[i+1]+n*1.0/(n-i);
            printf("%.2lf\n",dp[0]);
    }
}

Guess you like

Origin blog.csdn.net/qq_35975367/article/details/114701331