第五屆省賽題B—Circle (說白了就是規律題)

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.
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.5d[i+1]+0.5d[i-1] //任意一點通過上下兩點到達的概率都是1/2
d[n]=d[0]=0
d[i]=d[n-i] //後兩點利用了圓的對稱性
這個題這三點自己想到了但是卻沒有找到規律,最後在隊友的幫助下才發現的,這個規律真的是太神奇了

規律:
N 0 1 2 3 4 5 6 7 8 9
1 0
2 0 1
3 0 2 2
4 0 3 4 3
5 0 4 6 6 4

N 0 n-1 2n-4 3n-9
即求期望的遞歸

【代碼】:

#include <iostream>
#include <cstdio>
using namespace std;
const int N=2000;
double dp[N];


int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n,x;
        cin>>n>>x;
        if(x>n/2)
            x=n-x;
        dp[0]=0;
        for(int i=1;i<=x;i++)
            dp[i]=dp[i-1]+n-(2*i-1);

        printf("%.4lf\n",dp[x]);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章