『SPOJ FAVDICE』Favorite Dice (概率dp)

题目链接戳我

题目描述

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?


题目翻译

现在有1个N面的骰子,每次都会投出任意的一面,求投出所有面的期望次数。



解题思路

首先发现这是一道期望\(dp\)的题,然后记住这个!!!

概率正着求,期望倒着求!!!

我们假设\(dp[i]\)表示现在已经投出\(i\)面,到达最终状态的期望。

那么显然,\(dp[n]=0\),我们发现,当状态是\(i\)的时候,如果投出一次,那么有可能还是得到\(i\)面,也有可能得到\(i+1\)面。显然,得到\(i\)面的概率就是\(\frac{i}{n}\)\(i+1\)面的概率就是\(\frac{n-i}{n}\),得到这样的一个式子\(dp[i]=(dp[i]+1)*\frac{i}{n}+(dp[i+1]+1)*(\frac{n-i}{n})\),我们经过移项就可以得到\(dp[i]\)的值。



代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=1050;
double dp[maxn];
int t;
int main(){
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        dp[n]=0;
        for(register int i=n-1;i>=0;i--){
            dp[i]=(dp[i+1]*(n-i)/n+1)*n/(n-i);  
        }
        printf("%.2lf\n",dp[0]);
    }
}

猜你喜欢

转载自www.cnblogs.com/Fang-Hao/p/9595628.html