codeforces-148D-Bag of mice【概率】【DFS】

148D-Bag of mice

            time limit per test2 seconds    memory limit per test256 megabytes

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 exceed 10 - 9.

input
1 3
output
0.500000000

input
5 5
output
0.658730159

题目链接:cf-148D

题目大意:a,b两个人拿球,有w个白球,b个黑球。先拿到白球的人赢。a先开始拿球(不放回),然后b拿球,b拿球之后有一个球从袋子里逃出去,问a赢的概率。

题目思路:第i局a赢的概率为: a拿到白球的概率 + a拿到黑球 * b拿到黑球 * (一个黑球不见 + 一个白球不见)

以下是代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>
#include<iomanip>
using namespace std;
#define EPS 1e-6
map <int,double> mp[1005];
double dfs(int w,int b)
{
    if (mp[w][b]) return mp[w][b];  //记录访问过的w,b,不然会超时
    if (w <= 0) return 0;  //如果没有白球,那肯定不能赢
    if (b <= 0) return 1; //如果没有黑球,那肯定赢
    double all = w + b;
    double ans = 0; 
    ans += w * 1.0 / all;
    if (b >= 1 && all > 2) //取白球
    {
        ans += b * 1.0 / all * (b - 1) * 1.0 / (all - 1) * (w * 1.0 / (all - 2) * dfs(w - 1,b - 2));
    }  
    if (b >= 3 && all > 2)  //注意判断分母不能为0 //取黑球 
    {
        ans += b * 1.0 / all * (b - 1) * 1.0 / (all - 1) * ((b - 2) * 1.0 / (all - 2) * dfs(w,b - 3));
    }  
    mp[w][b] = ans; 
    return ans;
}
int main()
{
    int w,b;
    cin >> w >> b;
    printf("%.9f\n",dfs(w,b));
    return 0;
}

你可能感兴趣的:(CF,148D)