2014山东省第五届ACM省赛 Circle

Problem I: Circle

Time Limit: 2 Sec   Memory Limit: 64 MB
Submit: 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.

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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值