山东省第五届ACM省赛题——Circle(递推求概率)

来源:互联网 发布:贵金属软件 编辑:程序博客网 时间:2024/06/07 17:12

题目描述
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.
示例输入
3
3 2
5 4
10 5
示例输出
2.0000
4.0000
25.0000

史上最淫荡的递推!
首先可以得出结论d[i]=0.5*d[i-1]+0.5*d[i+1]+1,那么就先递推吧

#include <stdio.h>#include <math.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <sstream>#include <algorithm>#include <set>#include <queue>#include <stack>#include <map>#include <bitset>#define MAXN 10000010using namespace std;int n;double d[1010];void fun(){    memset(d,0,sizeof(d));    for(int t=0;t<5000;++t)        for(int i=1;i<n;++i)        d[i]=0.5*d[i+1]+0.5*d[i-1]+1.0;}int main(){    int t,x;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&x);        fun();        printf("%.4lf\n",d[x]);    }    return 0;}

我这里模拟走5000步,得出来的数据能过样例,据说当时省赛就有人这样过的,但现在在山东理工上过不了,不知道是不是后台数据加强了。。。但依然可以根据这个得到规律,下面是我得出的n为10的所有期望
50
10 0
0.0000
10 1
9.0000
10 2
16.0000
10 3
21.0000
10 4
24.0000
10 5
25.0000
10 6
24.0000
10 7
21.0000
10 8
16.0000
10 9
9.0000
10 10
0.0000
规律很明显了,就是d[i]=(n-1)+(n-3)+(n-5)…..接着我就过了

#include <stdio.h>#include <math.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <sstream>#include <algorithm>#include <set>#include <queue>#include <stack>#include <map>#include <bitset>#define MAXN 10000010using namespace std;int n;double d[1010];int main(){    int t,x;    scanf("%d",&t);    while(t--)    {        d[0]=0;        scanf("%d%d",&n,&x);        if(x>n/2)            x=n-x;        for(int i=1;i<=n/2;++i)            d[i]=d[i-1]+(n-(2*i-1));        printf("%.4lf\n",d[x]);    }    return 0;}
1 0
原创粉丝点击