codeforces 148 D Bag of mice(概率dp)

畫船聽雨發表於2014-07-08

題目大意:原來袋子裡有w只白鼠和b只黑鼠龍和王妃輪流從袋子裡抓老鼠。誰先抓到白色老師誰就贏。王妃每次抓一隻老鼠,龍每次抓完一隻老鼠之後會有一隻老鼠跑出來。每次抓老鼠和跑出來的老鼠都是隨機的。如果兩個人都沒有抓到白色老鼠則龍贏。王妃先抓。問王妃贏的概率。

解題思路:dp[i][j]表示現在輪到王妃抓時有i只白鼠,j只黑鼠,王妃贏的概率

王妃要想贏必須:第i次的時候王妃抓到白鼠,否則這個龍要抓到黑鼠王妃才有可能這輪不輸,而將會跑出去的老鼠有可能是白的,也有可能是黑色的。所以就產生了不同的狀態。記憶化搜一下。

D. Bag of mice
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance.

They take turns drawing a mouse from a bag which initially contains w white and b black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). Princess draws first. What is the probability of the princess winning?

If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.

Input

The only line of input data contains two integers w and b (0 ≤ w, b ≤ 1000).

Output

Output the probability of the princess winning. The answer is considered to be correct if its absolute or relative error does not exceed10 - 9.

Sample test(s)
input
1 3
output
0.500000000
input
5 5
output
0.658730159
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define eps 1e-7
//#define M 1000100
//#define LL __int64
#define LL long long
#define INF 0x3f3f3f3f
#define PI 3.1415926535898

const int maxn = 1010;

using namespace std;

double dp[maxn][maxn];

double dfs(int x, int y)
{
    if(dp[x][y] > 0)
        return dp[x][y];
    if(x < 0 || y < 0)
        return 0;
    if(x == 0)
        return 0;
    if(y == 0)
        return 1;
    double a = x*1.0;
    double b = y*1.0;
    double c = a+b;
    dp[x][y] = a/c;
    if(x+y >= 3)
    {
        dp[x][y] += (dfs(x-1, y-2)*(b/(c))*((b-1)/(c-1))*(a/(c-2)) + dfs(x, y-3)*(b/(c))*((b-1)/(c-1))*((b-2)/(c-2)));
    }
    return dp[x][y];

}

int main()
{
    int w, b;
    memset(dp, 0, sizeof(dp));
    while(cin >>w>>b)
    {
        printf("%.10lf\n",dfs(w,b));
    }
    return 0;
}


相關文章