BZOJ 2318: Spoj4060 game with probability Problem( 概率dp )

时间:2023-03-09 04:06:28
BZOJ 2318: Spoj4060 game with probability Problem( 概率dp )

BZOJ 2318: Spoj4060 game with probability Problem( 概率dp )

概率dp...

http://blog.csdn.net/Vmurder/article/details/46467899 ( from : [辗转山河弋流歌 by 空灰冰魂] )

这个讲得很好 , 推推公式就可以 O( n ) , 但是 n 最大是99999999 , 怎么破....其实 n 很大时概率基本不动了...所以只需计算到某一个较大值时就可以停下来了...

-------------------------------------------------------------------------------------

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#define clr( x , c ) memset( x , c , sizeof( x ) )
#define rep( i , n ) for( int i = 0 ; i < n ; ++i )
#define f( i ) ( p * g[ i - 1 ] + ( 1 - p ) * q * f[ i - 1 ] ) / ( 1 - ( 1 - p ) * ( 1 - q ) )
#define g( i ) ( q * f[ i - 1 ] + ( 1 - q ) * p * g[ i - 1 ] ) / ( 1 - ( 1 - p ) * ( 1 - q ) )
using namespace std;
const int maxn = 1005;
double f[ maxn ] , g[ maxn ]; // f : A first
int main() {
freopen( "test.in" , "r" , stdin );
int t , n;
double p , q;
for( scanf( "%d" ,&t ) ; t-- ; ) {
scanf( "%d%lf%lf" , &n , &p , &q );
n = min( n , 1000 );
f[ 0 ] = 0 , g[ 0 ] = 1;
for( int i = 1 ; i <= n ; i++ ) {
if( f[ i - 1 ] > g[ i - 1 ] ) 
   p = 1 - p , q = 1 - q;
f[ i ] = f( i );
g[ i ] = g( i );
if( f[ i - 1 ] > g[ i - 1 ] )
   p = 1 - p , q = 1 - q;
}
printf( "%.6lf\n" , f[ n ] );
}
    return 0; 

-------------------------------------------------------------------------------------

2318: Spoj4060 game with probability Problem

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 178  Solved: 66
[Submit][Status][Discuss]

Description

Alice和Bob在玩一个游戏。有n个石子在这里,Alice和Bob轮流投掷硬币,如果正面朝上,则从n个石子中取出一个石子,否则不做任何事。取到最后一颗石子的人胜利。Alice在投掷硬币时有p的概率投掷出他想投的一面,同样,Bob有q的概率投掷出他相投的一面。

现在Alice先手投掷硬币,假设他们都想赢得游戏,问你Alice胜利的概率为多少。

Input

第一行一个正整数t,表示数据组数。

对于每组数据,一行三个数n,p,q。

Output

对于每组数据输出一行一个实数,表示Alice胜利的概率,保留6位小数。

Sample Input

1

1 0.5 0.5

Sample Output

0.666667

HINT

数据范围:

1<=t<=50

0.5<=p,q<=0.99999999

对于100%的数据 1<=n<=99999999

Source