2014年山东省第五届ACM大学生程序设计竞赛-B-Circle

来源:互联网 发布:平面设计有什么软件 编辑:程序博客网 时间:2024/05/16 04:54

Circle

Time Limit: 2000ms   Memory limit: 65536K  

题目描述

You have been given a circle from 0 to n - 1. If you are currently at x, you will move to (x - 1) mod n or (x + 1) mod n with equal probability. Now we want to know the expected number of steps you need to reach x from 0.

输入

The first line contains one integer T — the number of test cases.
 
Each of the next T lines contains two integers n, x (0  ≤ x < n ≤ 1000) as we mention above.

输出

For each test case. Print a single float number — the expected number of steps you need to reach x from 0. The figure is accurate to 4 decimal places.

示例输入

33 25 410 5

示例输出

2.00004.000025.0000

提示

 

来源

2014年山东省第五届ACM大学生程序设计竞赛

思路

题意:有一个环,共有n个节点,从0标号到n-1,首尾相连,给定任意标号x,在非x点向左和向右走的概率相等,均为1/2,走到x点停止,那么从0点走到x点的数学期望是多少。
首先我们假设n=5,x=1,那么在非x点必然选择向右或者左走一步,对于在每一点的数学期望则有
E0=1+(E4+E1)/2;
E1=0;
E2=1+(E1+E3)/2;
E3=1+(E2+E4)/2;
E4=1+(E3+E0)/2;
等式两边分别想加得
E0+E1+E2+E3+E4=1+(E4+E1)/2+0+1+(E1+E3)/2+1+(E2+E4)/2+1+(E3+E0)/2;
即E0+E2=2*(5-1);根据对称性显然E0=E2;故E0=E2=5-1=4;
我们可以推理到任意一种情况
均可得到等式
E(x+n-1)%n+E(x+1)%n=2*(n-1);根据对称性均有E(x+n-1)%n=E(x+1)%n=n-1;
然后我们分别根据等式在已知E0,E1的数学期望下求E4,根据E0,E4求E3。。。


示例代码

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn(1e3+10);long double probablity[maxn];//代表数学期望int n,x;void fun(int loc)//本函数还可以优化为到loc是0时停止{    if(probablity[(loc+1)%n]==-1)    {        probablity[(loc+1)%n]=2*probablity[loc]-2-probablity[(loc+n-1)%n];        fun((loc+1)%n);    }}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&x);        for(int i=0; i<n; i++)            probablity[i]=-1;//初始化为-1,即还未进行计算        probablity[x]=0;        probablity[(x+1)%n]=n-1;        probablity[(x+n-1)%n]=n-1;        fun((x+1)%n);        double ans=(double)probablity[0];        printf("%.4f\n",ans);    }    return 0;}/**************************************    Problem id  : SDUT OJ 2878    User name   : crawl    Result      : Accepted    Take Memory : 560K    Take Time   : 0MS    Submit Time : 2016-05-20 18:16:24**************************************/



0 0