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

 

题意:t 组数据,每组给出 n 个数,代表 n 个格子的值,现在要从第一个格子出发前往第 n 个格子,每到达一个格子都能扔一次 1~6 的骰子,决定下一步走到哪个位置,若当前位置+骰子掷出的值>n 则重新掷骰子,直到到达第 n 个格子结束,问从最终获得格子上的值的期望值。

思路:因为这道题是让我们求期望,而一般期望值都是通过逆推来得到的,所以从后向前推时,走过的点是一定能拿到的,因此令每个的点的初始期望值等于每个点的初始值,即:dp[i]=num[i]

然后我们能得出规律: dp[i]=dp[i]+dp[i+j]/ans,最后得到的 dp[1] 就是最终的期望值。

AC代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
typedef long long ll;
const int maxx=10010;
const int inf=0x3f3f3f3f;
using namespace std;
double num[maxx];
double dp[maxx];
int main()
{
    int t;
    cin>>t;
    int k=1;
    while(t--)
    {
        int n;
        cin>>n;
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            cin>>num[i];
            dp[i]=num[i];
        }
        for(int i=n-1;i>=1;i--)
        {
            for(int j=1;j<=6;j++)
            {
                int ans=min(6,n-i);
                if(i+j<=n)
                    dp[i]=dp[i]+dp[i+j]/ans;
            }
        }
        cout<<"Case"<<" "<

 

你可能感兴趣的:(动态规划-期望,概率DP,期望,概率DP)