题目如下:
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
题意:从1位置开始走直达到达N位置所能够获得的金币的期望。
题目思路:关于期望DP的问题必须要逆向来处理,因为概率只能从已知求得未知,只有从N点出发的期望是一定确定的。于是设DP[I]为从I点出发时获得的金币的期望。状态转移方程为:
p[k] = 1 / min(m,6) * (dp[k + 1] + dp[k+2] + … + dp[min(m,6)]) + gold[k]
完整的代码如下:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <set>
#include <cmath>
using namespace std;
const int maxn = 200010;
const int maxn2= 110;
const int inf =0x3f3f3f3f;
const int mod = 10007;
int s[maxn2];
double dp[maxn2];
int n,t;
int main()
{
scanf("%d",&t);
int ans=0;
while(t--){
scanf("%d",&n);
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
scanf("%d",&s[i]);
dp[i]=s[i];
}
for(int i=n;i>=1;i--){
if(n-i>=6){
for(int j=i+1;j<=n&&i+6>=j;j++) {
dp[i] += ((1.0 / 6) * dp[j]);
}
}else{
int a=n-i;
for(int j=i+1;j<=n&&i+6>=j;j++) {
dp[i] += ((1.0/a) * dp[j]);
}
}
}
ans++;
printf("Case %d: %.7f\n",ans,dp[1]);
}
return 0;
}