Discovering Gold LightOJ - 1030 (概率dp)

You are in a cave, a long cave! The cave can be represented by a 1 x N grid. Each cell of the cave can contain any amount of gold.

Initially you are in position 1. Now each turn you throw a perfect 6 sided dice. If you get X in the dice after throwing, you add X to your position and collect all the gold from the new position. If your new position is outside the cave, then you keep throwing again until you get a suitable result. When you reach the Nth position you stop your journey. Now you are given the information about the cave, you have to find out the expected number of gold you can collect using the given procedure.

Input
Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case contains a blank line and an integer N (1 ≤ N ≤ 100) denoting the dimension of the cave. The next line contains N space separated integers. The ith integer of this line denotes the amount of gold you will get if you come to the ith cell. You may safely assume that all the given integers will be non-negative and no integer will be greater than 1000.

Output
For each case, print the case number and the expected number of gold you will collect. Errors less than 10-6 will be ignored.

Sample Input
3
1
101
2
10 3
3
3 6 9

Sample Output
Case 1: 101.0000000000

Case 2: 13.000

Case 3: 15

题目大意:一共有n个格子,1~n的格子中分别有着不同数量的黄金,最初时,你位于第一个格子,而且你有一个骰子,每次掷出的数字x的概率是相同的。然后你会前进x步到达一个新格子,并且拿掉新格子中的黄金,如果你掷出骰子后将要跳出所有格子,你必须重新掷骰子,直到到达n位置这个格子(即最后一个格子)。问拿走金子的期望值是多少。

思路:很显然,我们在第i个位置,掷出骰子后最多能走到loc=min(i+6,n);所以我们不难得知,我们在第i个位置时期望的公式,我们设len是在第i位置时最多能走的步数 len(i)=min(n-i,6);所以E(i)=E(i+1)/len(i)+E(i+2)/len(i)+E(i+3)/len(i)+…+E(loc)/len(i)(注意这里需要考虑i+6>n的情况);所以我们可以倒着推出E(1),E(1)就是答案。那为什么不能用Ei=E(i-1)/6+E(i-2)/6+E(i-3)/6+E(i-4)/6+E(i-5)/6+E(i-6)/6进行计算呢?我说不行就是不行!! 因为题目要求是从1开始的,这样不一定满足从1开始的条件。
可以解释样例一下样例三,3 6 9三个数,从最后开始算起,E(3)=9,E(2)=6+9/1=15,E(1)=3+15/2+9/2=15,E(1)为15即为答案。

上代码(写的很丑啊!!!

#pragma GCC optimize(2)
#include 
using namespace std;
typedef long long ll;
const int maxn=1e6+7;
const int mod=1e9+7;
ll m,n,i,j;
double dp[maxn];
double a[maxn];
int main()
{
	ll t,k;
	cin>>t;
	for(k=1;k<=t;k++)
	{
		memset(dp,0,sizeof(dp));
		cin>>n;
		for(ll i=1;i<=n;i++)
		{
			cin>>a[i];
		}
		dp[n]=a[n];
		for(ll i=n-1;i>=1;i--)
		{
			dp[i]+=a[i];
			ll len=min(n-i,6*1ll);
			for(ll j=i+1;j<=min(i+6,n);j++)
				dp[i]+=dp[j]/len;
		}
		printf("Case %lld: ",k);
		printf("%.8lf\n",dp[1]);
	}
	return 0;
}

你可能感兴趣的:(概率dp)