1+ // ECPC 2017
2+ // AC
3+
4+ #include < bits/stdc++.h>
5+ using namespace std ;
6+
7+ int N;
8+ long double p;
9+ int x,y,k;
10+
11+ long double dp[50 ][50 ][3001 ];
12+ int vis[50 ][50 ][3001 ];
13+ int t;
14+
15+ bool valid_move (int pos_x, int pos_y)
16+ {
17+ if (pos_x < 0 || pos_y < 0 || pos_x == N || pos_y == N || pos_x==pos_y)
18+ return 0 ;
19+ return 1 ;
20+ }
21+
22+ long double solve (int pos_x, int pos_y, int rem_r)
23+ {
24+ if (pos_x < 0 || pos_y < 0 || pos_x == N || pos_y == N || pos_x==pos_y)
25+ return 0 ;
26+ if (vis[pos_x][pos_y][rem_r] == t)
27+ return dp[pos_x][pos_y][rem_r];
28+
29+ vis[pos_x][pos_y][rem_r] = t;
30+ if (rem_r == 0 )
31+ {
32+ if (pos_x == x && pos_y == y)
33+ return dp[pos_x][pos_y][rem_r] = 1 ;
34+ return dp[pos_x][pos_y][rem_r] = 0 ;
35+ }
36+ // probability of each pair = 1 / nC2
37+ long double prob_round = 1.0 / (N-1 );
38+ long double ans = (1 -p) * solve (pos_x, pos_y, rem_r -1 );
39+ int valid_moves = 0 ;
40+
41+ if (abs (pos_x-pos_y) == 1 )
42+ {
43+ // adjancent
44+ ans += prob_round * p * solve (pos_y, pos_x, rem_r - 1 );
45+ if (valid_move (pos_y, pos_x))
46+ valid_moves ++;
47+ }
48+ ans += prob_round * p * solve (pos_x-1 , pos_y, rem_r - 1 );
49+ ans += prob_round * p * solve (pos_x+1 , pos_y, rem_r - 1 );
50+ ans += prob_round * p * solve (pos_x, pos_y-1 , rem_r - 1 );
51+ ans += prob_round * p * solve (pos_x, pos_y+1 , rem_r - 1 );
52+
53+ int dx []= {-1 , 1 , 0 , 0 };
54+ int dy []= {0 , 0 , -1 , 1 };
55+ for (int i=0 ;i<4 ;i++)
56+ {
57+ if (valid_move (pos_x+dx[i], pos_y+dy[i]))
58+ valid_moves++;
59+ }
60+ // Prob of same location = ??
61+
62+ ans += (N-1 - valid_moves) * prob_round * p * solve (pos_x, pos_y, rem_r - 1 );
63+ return dp[pos_x][pos_y][rem_r] = ans;
64+ }
65+
66+ long double dp_1[50 ][3001 ];
67+ int vis_1[50 ][3001 ];
68+
69+ long double solve_1 (int pos_x, int rem_r)
70+ {
71+ if (pos_x <0 || pos_x == N)
72+ return 0 ;
73+ if (vis_1[pos_x][rem_r] == t)
74+ return dp_1[pos_x][rem_r];
75+ if (rem_r == 0 )
76+ {
77+ return dp_1[pos_x][rem_r] = (pos_x == x);
78+ }
79+ vis_1[pos_x][rem_r] = t;
80+ long double ans = (1 -p) * solve_1 (pos_x, rem_r -1 );;
81+ long double prob_round = 1.0 / (N-1 );
82+ ans += prob_round * p * solve_1 (pos_x - 1 , rem_r - 1 );
83+ ans += prob_round * p * solve_1 (pos_x + 1 , rem_r - 1 );
84+ if (pos_x == 0 || pos_x == N-1 )
85+ ans += (N-2 ) * prob_round * p * solve_1 (pos_x, rem_r - 1 );
86+ else
87+ ans += (N-3 ) * prob_round * p * solve_1 (pos_x, rem_r - 1 );
88+ return dp_1[pos_x][rem_r] = ans;
89+ }
90+ int main ()
91+ {
92+ int T;
93+ freopen (" in.txt" , " r" , stdin);
94+ cin>>T;
95+ for (t=1 ;t<=T;t++)
96+ {
97+ cin>>N>>p>>x>>y>>k;
98+
99+ long double ans = 1 ;
100+ if (N==1 )
101+ ans = 1 ;
102+ else if (x==y)
103+ ans = solve_1 (x, k);
104+ else
105+ ans = solve (y, x, k);
106+ printf (" Case %d: %0.5LF\n " , t, ans);
107+ // cout<<fixed<<setprecision(5)<<solve<<"\n";
108+ }
109+
110+ }
0 commit comments