zoj 2271 Chance to Encounter a Girl <概率DP>

题目: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2271

题意:一个N*N的矩阵( N = 2*k-1 , k<=50) , 有一个 MM 站在矩阵的中央(k,k),MM 可以朝上下左右四个方向走动,不能走出去,

而 you 首先站在(0,k)的位置上,you每次只能向右走一步,求you遇到MM的概率~

思路: dp[t][x][y]  表示MM在t时刻到达坐标为 (x, y) 的概率,

    那么 dp[t][x][y] = dp[t-1][x'][y']*p(x', y')  , p(x', y') 表示在坐标(x,'  y')时走到坐标(x, y)的概率~

    初始化 dp[0][k][k]=1; 

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 const int dir[ 4 ][ 2 ] = {1,0,0,1,-1,0,0,-1};
 6 double dp[110][110][110];
 7 int N;
 8 double F( int x, int y )
 9 {
10     if( x<0||y>=N )return -1;
11     if( (x==0&&y==0) || (x==0&&y==N-1)
12        || (x==N-1&&y==0) || (x==N-1&&y==N-1))return 2.0;
13     if( x==0 || y==0 || x==N-1 || y==N-1 ) return 3.0;
14     return 4.0;
15 }
16 int main( )
17 {
18     while(scanf("%d", &N)!= EOF){
19         double ans=0;
20         if(N%4==1){
21             printf("%.4lf
", ans);
22             continue;
23         }
24         memset(dp, 0, sizeof dp);
25 
26         dp[0][N/2][N/2]=1;
27 
28         for( int t=0; t<N; ++ t ){
29         for( int i=0; i<N; ++ i ){
30         for( int j=0; j<N; ++ j ){
31             for(int k=0; k<4; ++ k){
32                 int x=i+dir[k][0], y=j+dir[k][1];
33                 if( F(x, y)>0 )
34                     dp[t+1][i][j]+=dp[t][x][y]/F(x,y);
35             }
36             if( i==N/2 && j==t ){
37                 ans+=dp[t+1][i][j];
38                 dp[t+1][i][j]=0;
39             }
40         }
41         }
42         }
43         printf("%.4lf
", ans);
44    }
45     return 0;
46 }
View Code

   

原文地址:https://www.cnblogs.com/jian1573/p/3243592.html