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.
示例输入
3 3 2 5 4 10 5
示例输出
2.0000 4.0000 25.0000
提示
来源
2014年山东省第五届ACM大学生程序设计竞赛
题意:n个数围成一个圈,编号0~n-1,从一个数到其上一个和下一个的数的概率相同(即都是0.5)。给出n,求从0出发到达一个数x所需要的步数的数学期望。
思路:这里用递推可以水一下。
首先可以确定三个结论
d[i]=0.5*d[i+1]+0.5*d[i-1]
d[n]=d[0]=0
d[i]=d[n-i]
规律:
d[0]=0,d[1]=n-1,d[2]=(n-1)+(n-3),d[3]=(n-1)+(n-3)+(n-5),……。
这样就可以递推了。
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
int T;
int n,x;
int i;
double d[1005];
d[0]=0;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&x);
if(x>n/2){
x=n-x;
}
for(i=1;i<=x;++i){
d[i]=d[i-1]+(n-(2*i-1));//这个递推公式很神奇。。。
}
printf("%.4f\n",d[x]);
}
return 0;
}