STDU 2878 概率dp
2015-03-17 19:33
99 查看
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大学生程序设计竞赛示例程序
分析:对于这种类型的概率题,直接迭代系数比较好!!我们可以用dp[i]表示当前在i点到达x点的期望步数,那么显然dp[x]=0.同时 dp[0]即为所求;
以x为轴,左右两边同时迭代到0的时候就可得到方程:
dp[0]=A1[0]*dp[n-1]+B1[0]
dp[n-1]=A2[n-1]*dp[0]+B2[n-1]
(其中A1[0],A2[n-1],B1[0],B2[n-1]都是常数)
#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <algorithm> using namespace std; const int maxn=1100; int n,x; double A1[maxn],B1[maxn]; double A2[maxn],B2[maxn]; void solve() //迭代运算 { A1[x-1]=1.0/2,B1[x-1]=1.0; for(int i=x-2;i>=0;i--) //最终 dp[0]=A1[0]*dp[(0-1+n)%n]+B1[0] { double tmp=1.0-0.5*A1[i+1]; A1[i]=0.5/tmp; B1[i]=(1.0+0.5*B1[i+1])/tmp; } if(x==n-1) { A2[6]=0.0; B2[6]=0.0; } else { A2[x+1]=1.0/2,B2[x+1]=1.0; for(int i=(x+2)%n; i!=0;i=(i+1)%n) { double tmp=1.0-0.5*A2[i-1]; A2[i]=0.5/tmp; B2[i]=(1.0+0.5*B2[i-1])/tmp; } } double ans=(A1[0]*B2[n-1]+B1[0])/(1-A1[0]*A2[n-1]); printf("%.4lf\n",ans); } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&x); if( x==0 || n==1) { printf("0.0000\n"); continue; } if(n==2) { printf("1.0000\n"); continue; } solve(); } return 0; }
相关文章推荐
- Codeforces 148D Bag of mice:概率dp 记忆化搜索
- codeforces 768 D Jon and Orbs(概率dp)
- HDU 4405 概率期望DP
- hdu5001 Walk (概率dp)
- 某不知名的题 - 概率DP
- poj 3756 Chess Game 模拟型概率dp
- ZOJ 3329 One Person Game(概率DP,求期望)
- POJ 3744 Scout YYF I (矩阵优化,分段计算的概率DP)
- POJ 2096 Collecting Bugs(概率DP求期望)
- CodeForces 167B - Wizards and Huge Prize 期望概率dp
- UVA 1456 Cellular Network 贪心+概率dp
- 例10-12 *uva1637(概率dp)
- POJ 2151 Check the difficulty of problems 概率DP
- hdu4405Aeroplane chess【概率DP】
- 概率dp
- [概率DP] BZOJ4008: [HNOI2015]亚瑟王
- bzoj 4820: [Sdoi2017]硬币游戏 概率dp+高斯消元+KMP
- POJ 2151 Check the difficulty of problems 概率DP
- POJ 2151 概率DP
- 【HDU】4870 Rating 概率DP