题意:有一个W列H行的竞技场,机器人要从(1,1)走到(W,H)。竞技场中有一个左上坐标(L,U),右下坐标(R,D)的矩形黑洞。
机器人只能向右走或向下走,概率各为1/2。如果机器人在最后一行,则只能往右走;如果机器人在最后一列,则只能往下走。
问机器人不掉进黑洞成功到达(W,H)的概率。
数据范围:
1 ≤ T ≤ 100. 1 ≤ U ≤ D ≤ H. 1 ≤ L ≤ R ≤ W. 1 ≤ W ≤ 10^5. 1 ≤ H ≤ 10^5.
分析:机器人要么从黑洞左下方绕过去,要么从黑洞右上方绕过去,时间复杂度O(n)。
注意:由于“如果机器人在最后一行,则只能往右走;如果机器人在最后一列,则只能往下走”,因此最后一行和最后一列的概率一定要单独算!
#include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #include<string> #include<iostream> #include<set> #include<map> #include<stack> #include<queue> #include<vector> #include<sstream> typedef long long LL; const int INF = 0x3f3f3f3f; using namespace std; const int MAXN = 200000 + 10; const double eps = 1e-8; int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a < b ? -1 : 1; } double Log2[MAXN], last_r[MAXN], last_c[MAXN]; int W, H, L, U, R, D; void init_log2(){ Log2[0] = 0; for(int i = 1; i < MAXN; ++i){ Log2[i] = Log2[i - 1] + log2(i); } } void init_last(){ last_r[1] = pow(2, Log2[1 + H - 2] - Log2[1 - 1] - Log2[H - 1] - (double)(1 + H - 2)); for(int i = 2; i <= W; ++i){ last_r[i] = last_r[i - 1] + 0.5 * pow(2, Log2[i + (H - 1) - 2] - Log2[i - 1] - Log2[(H - 1) - 1] - (double)(i + (H - 1) - 2)); } last_c[1] = pow(2, Log2[W + 1 - 2] - Log2[W - 1] - Log2[1 - 1] - (double)(W + 1 - 2)); for(int i = 2; i <= H; ++i){ last_c[i] = last_c[i - 1] + 0.5 * pow(2, Log2[(W - 1) + i - 2] - Log2[(W - 1) - 1] - Log2[i - 1] - (double)((W - 1) + i - 2)); } } bool judge(int x, int y){ return x >= 1 && x <= W && y >= 1 && y <= H; } int main(){ init_log2(); int T; scanf("%d", &T); for(int Case = 1; Case <= T; ++Case){ scanf("%d%d%d%d%d%d", &W, &H, &L, &U, &R, &D); init_last(); int x = L - 1; int y = D + 1; double ans = 0; while(judge(x, y)){ if(y == H){ ans += last_r[x]; } else{ ans += pow(2, Log2[x + y - 2] - Log2[x - 1] - Log2[y - 1] - (double)(x + y - 2)); } --x; ++y; } x = R + 1; y = U - 1; while(judge(x, y)){ if(x == W){ ans += last_c[y]; } else{ ans += pow(2, Log2[x + y - 2] - Log2[x - 1] - Log2[y - 1] - (double)(x + y - 2)); } ++x; --y; } printf("Case #%d: %.8lf\n", Case, ans); } return 0; }