Problem I: Circle
Time Limit: 2 Sec Memory Limit: 64 MBSubmit: 68 Solved: 39
[ Submit][ Status][ Web Board]
Description
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.
Input
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.
Each of the next T lines contains two integers n, x (0 ≤ x < n ≤ 1000) as we mention above.
Output
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.
Sample Input
3
3 2
5 4
10 5
Sample Output
2.0000
4.0000
25.0000
题意: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 <cstdio>
using namespace std;
typedef long long ll;
int t;
int n, x;
double d[1005];
int main()
{
scanf("%d", &t);
while (t--){
scanf("%d%d", &n, &x);
if (x > n / 2)
x = n - x;
d[0] = 0;
for (int i = 1; i <= x; i++)
d[i] = d[i - 1] + (n - (2 * i - 1));
printf("%.4lf\n", d[x]);
}
return 0;
}