HDU 4987(概率dp)

Little Pony and Dice

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 489    Accepted Submission(s): 139


Problem Description
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.

The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with same probability. Also she knows that each toss is independent from others.

There is n + 1 cells in total, number from 0 to n, Twilight Sparkle race her token from 0 to n according to die rolls. The game end once she move to n or over it. Help Twilight Sparkle calculated the probability she end the game exactly at n.
 

Input
Input contains multiple test cases (less than 200). 
For each test case, only one line contains two integers m and n (1<=m, n<=10^9).
 

Output
For each case, output the corresponding result, rounded to 5 digits after the decimal point.
 

Sample Input
3 5 6 10
 

Sample Output
0.49794 0.28929
 

Source
 

題目鏈接:
hdu 4987


題目描述:

大富翁遊戲,多組輸入m,n兩個值,m表示篩子的最大點數,n表示格子數的最大編號(從0開始,總共n+1個各自)。當走到格子編號大於或等於n時則勝利。

求出當勝利時剛好到達n點時的概率。


解題思路:

這道題是概率dp,dp[i]表示剛好到達i時的概率。dp[0]=1,能到達dp[i-1]的點除了i-1-m外都能到達dp[i]。dp[i]=dp[i-1]+dp[i-1]*1.0/m,當i>m時dp[i]-=dp[i-m-1]*1.0/m。

當n的值越大時,dp[i-1]與dp[i]的值相當接近,所以可以用一個定值來表示。代碼中用前後差值小於1e-13來表示非常小。


AC代碼:

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <algorithm>
#define eps 1e-13
#define maxn 703000
//#define zero(x) (fabs(x)<eps?0:x)

using namespace std;

typedef long long LL;

double zero(double x)
{
    return ((fabs(x)<eps)? 0:x);
}
double dp[maxn];
int main()
{
    LL m,n;
    while(cin >> m >> n)
    {
        dp[0]=1.0;//初始位置概率爲1
        dp[1]=1.0/m;
        int i;
        for(i=2;i<=n;i++)
        {
            dp[i]=dp[i-1]+dp[i-1]*1.0/m;//轉移公式
            if(i>m)
                dp[i]=dp[i]-dp[i-m-1]*1.0/m;//將i-m-1概率的貢獻刪去
            if((zero(dp[i]-dp[i-1]))==0)//當i足夠大師直接輸出
            {
                printf("%.5lf\n",dp[i]);
                break;
            }

        }
        if(i>n)
            printf("%.5lf\n",dp[n]);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章