2014山东省第五届ACM省赛 Circle

34 篇文章 6 订阅

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值