LightOj-1030 Discovering Gold (期望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

题解:

起始位置是1,从1走到n,给你一个骰子(6个面),按点数走,收集每一点上的金子,如果你将要走到的位置在n之内,就继续扔,往前走,如果在n之外,就一直扔到合适的位置为止,求到达n点时的期望

 这个题是一个求期望的题,那么值得注意的是,当扔在n之外的情况是无效的,所以我们在位置i<n6i<n−6的时候 此时的概率应该为 1/(n-i),当我们在算权值的时候,我们发现对于位置i来说,它可以到i+1,i+2,i+6i+1,i+2,……,i+6 这些点,而这些点的权值又与他们后面6个点相关,因此我们倒过来从最后一个点开始求,最后一个点是一定会取的,于是我们就用一个dp数组把他计算一下;

参考代码为:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int T,n;
 4 double dp[110];
 5 
 6 int main()
 7 {
 8     scanf("%d",&T);
 9     for(int k=1;k<=T;k++)
10     {
11         scanf("%d",&n);
12         memset(dp,0,sizeof dp);
13         for(int i=1;i<=n;i++) scanf("%lf",dp+i);
14         for(int i=n-1;i>=1;i--)
15         {
16             for(int j=1;j<=6;j++) dp[i]+=dp[i+j]/(1.0*min(6,n-i));
17         }
18         printf("Case %d: %.10lf
",k,dp[1]);
19     }
20     
21     return 0;
22 }
View Code
原文地址:https://www.cnblogs.com/csushl/p/9483740.html