[测试题]圆圈

Description

现在有一个圆圈,顺时针标号分别从 0 到 n-1,每次等概率顺时针走一步或者逆时针走一步,即如果你在 i 号点,你有 1/2 概率走到((i-1)mod n)号点,1/2 概率走到((i+1)mod n)号点。问从 0 号点走到 x 号点的期望步数。

Input

第一行包含一个整数 T,表示数据的组数。
接下来有 T 行,每行包含两个整数 n, x。
T<=10, 0<=x<n<=300;​​,a2​​an​​ 和 bbb,代表一组方程。

Output

对于每组数据,输出一行,包含一个四位小数表示答案。

Sample Input

3
3 2
5 4
10 5

Sample Output

2.0000
4.0000
25.0000

HINT

对于 30% 的数据,n<=20
对于 50% 的数据,n<=100
对于 70% 的数据,n<=200
对于 100%的数据,n<=300

题解

高斯消元,$n$个方程,$n$个未知量, 设$E[ p ]$ 为从$p$节点走到$x$节点还需要走的步数的期望数。那么$E [ x ] = 0$;

对于每个节点都有   $E[p]=0.5*E[p-1]+0.5*E[p+1]+1$,  即  $-0.5*E[p-1]+E[p]-0.5*E[p+1]=1$。

模板套上一题的就好了。

 1 //It is made by Awson on 2017.10.10
 2 #include <set>
 3 #include <map>
 4 #include <cmath>
 5 #include <ctime>
 6 #include <cmath>
 7 #include <stack>
 8 #include <queue>
 9 #include <vector>
10 #include <string>
11 #include <cstdio>
12 #include <cstdlib>
13 #include <cstring>
14 #include <iostream>
15 #include <algorithm>
16 #define LL long long
17 #define Min(a, b) ((a) < (b) ? (a) : (b))
18 #define Max(a, b) ((a) > (b) ? (a) : (b))
19 #define sqr(x) ((x)*(x))
20 using namespace std;
21 const int N = 300;
22 
23 int n, d;
24 double a[N+5][N+5];
25 
26 void Gauss() {
27   for (int line = 1; line <= n; line++) {
28     int Max_line = line;
29     for (int i = line+1; i <= n; i++)
30       if (fabs(a[i][line]) > fabs(a[Max_line][line]))
31     Max_line = i;
32     if (Max_line != line) swap(a[line], a[Max_line]);
33     if (a[line][line] == 0) {
34       printf("No Solution\n");
35       return;
36     }
37     for (int i = line+1; i <= n; i++) {
38       double tmp = a[i][line]/a[line][line];
39       for (int j = line; j <= n+1; j++)
40     a[i][j] -= a[line][j]*tmp;
41     }
42   }
43   for (int i = n; i >= 1; i--) {
44     for (int j = i+1; j <= n; j++)
45       a[i][n+1] -= a[j][n+1]*a[i][j];
46     a[i][n+1] /= a[i][i];
47   }
48   printf("%.4lf\n", a[1][n+1]);
49 }
50 void work() {
51   scanf("%d%d", &n, &d);
52   memset(a, 0, sizeof(a));
53   for (int i = 0; i < n ;i++) {
54     if (i == d) {
55       a[i+1][i+1] = 1;
56       a[i+1][n+1] = 0;
57     }else {
58       a[i+1][i+1] = 1;
59       a[i+1][(i-1+n)%n+1] = -0.5;
60       a[i+1][(i+1)%n+1] = -0.5;
61       a[i+1][n+1] = 1;
62     }
63   }
64   Gauss();
65 }
66 int main() {
67   int t; scanf("%d", &t);
68   while (t--) work();
69   return 0;
70 }

 

转载于:https://www.cnblogs.com/NaVi-Awson/p/7646226.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值