Discovering Gold
Time Limit: 2 second(s) Memory Limit: 32 MB

Program Description
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


101 

10 3 

3 6 9

Output for Sample Input
Case 1: 101.0000000000 
Case 2: 13.000 
Case 3: 15

题意:

n个格子以及每个格子上的金币,你从第一个格子出发,每次掷1-6的骰子,根据掷出的值前进。若当前位置 + 掷出的值 > n,则重新掷骰子,到达第n个格子游戏结束。问你获得金币值的期望。

分析:

期望DP的最大特点:逆求期望,正求概率。

以这题为例,解释一下期望为啥要逆求。一下

//我们假设格子和值都是一样,所以下述的话,值就是格子,格子就是值。。。

比如这样的9个格子,我们从后往前

对于第9个格子,因为只有9,能取的期望就是E[9]=9; 对于第8个格子,8是一定要取的,而9也是一定回取的,所以对于第8个格子,期望就是E[8]=17; 对于第7个格子,7是一定要取的,对于后面可能是直接取了9,或者先取8再取9,情况是满足,对于每种情况概率是1/2,所以就是7+9/2+(8+9)/2=7+E[9]/2+E[8]/2=20;

PS: 上面的情况,在7后面的时候,我们可能取9,或者先取8,那么其实就是拿了第8个格子的期望和第9个格子期望,期望就是能取的值,然后*概率,全部情况的总和就是新的期望,有人会奇怪那7呢?我们的前提是对于第7格一定拿7啊;对于第6个格子,那么就是6一定要拿的,然后会拿7,拿8,拿9,他们的期望*概率的总和+他能取的值就是6的第6个格子的期望=期望的和*概率(因为只骰子,所以概率都相等)+他能取的值就是6的第6个格子的期望;...以此类推; 所以我们设dp[i]直接为期望。

 

import java.util.Scanner;

public class Main {
static double [] dp=new double[105];

public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int cas=0;
int T=in.nextInt();
while(T-->0){
cas++;
int n=in.nextInt();
for(int i=1;i<=n;i++)
{
dp[i]=in.nextDouble();
}
for(int i=n-1;i>=1;i--)
{
double temp=0.0;
int k=Math.min(6, n-i);//最大为6
for(int j=i+1;j<=i+k;j++)
temp+=dp[j];


dp[i]=dp[i]+1.0*temp/k;
}

System.out.print("Case "+cas+": ");
System.out.printf("%.10f",dp[1]);
System.out.println();
}
System.gc();
}


}