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-6,min(n,筛子的个数+你现在格子标号)=你下一个格子的标号。
每一个格子都有一定金币,求获得的金币期望。
思路:
倒着从N开始推,然后对于每一个位置k,看后面的min(n-i-1,6)=sum1个格子的期望,dp[i]是i个格子的期望:
公式就是 (1.0/sum1)*(dp[k+1]+dp[k+2]+...+dp[sum1]),这样才能推出来。从前往后推好像写不出来....
从后往前推推到第一个就是答案了,因为这样比较简单吧。
#include<bits/stdc++.h>
using namespace std;
double ans[1000];
int num[1000];
int main()
{
int t;
cin>>t;
for(int k=1;k<=t;k++)
{
int n;
cin>>n;
memset(ans,0,sizeof(ans));
memset(num,0,sizeof(num));
for(int i=0;i<n;i++)
{
cin>>num[i];
}
for(int i=0;i<n-1;i++)
ans[i]=0;
ans[n-1]=num[n-1];
for(int i=n-2;i>=0;i--)
{
ans[i]=num[i];
int sum=min(6,n-i-1);
for(int j=1;j<=sum;j++)
{
ans[i]+=1.0/sum*ans[i+j];
}
}
printf("Case %d: %.8lf\n",k,ans[0]);
}
}