1030 - Discovering Gold (lightoj 1030 概率DP)

1030 - Discovering Gold
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB

You are in a cave, a long cave! The cave can be representedby 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 youthrow a perfect 6 sided dice. If you get X in the dice afterthrowing, you add X to your position and collect all the gold from thenew position. If your new position is outside the cave, then you keep throwingagain until you get a suitable result. When you reach the Nthposition you stop your journey. Now you are given the information about thecave, you have to find out the expected number of gold you can collectusing 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 linecontains N space separated integers. The ith integerof this line denotes the amount of gold you will get if you come to the ithcell. You may safely assume that all the given integers will be non-negativeand no integer will be greater than 1000.

Output

For each case, print the case number and the expected numberof gold you will collect. Errors less than 10-6 will beignored.

设在i处的期望为E(i)


E(i) = (E(i+1) + E(i+2) + E(i+3) + E(i+4) + E(i+5) + E(i+6)) / 6 + gold[i];

逆向递推就可以了


/***********************************************
 * Author: fisty
 * Created Time: 2015-08-04 21:09:25
 * File Name   : 1030.cpp
 *********************************************** */
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define Debug(x) cout << #x << " " << x < P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define lson l, m, k<<1
#define rson m+1, r, k<<1|1
#define MAX_N 110
int t;
int n;
int a[MAX_N];
double dp[MAX_N];
int cnt;
int main() {
    //freopen("in.cpp", "r", stdin);
    //cin.tie(0);
    //ios::sync_with_stdio(false);
    scanf("%d", &t);
    cnt = 1;
    while(t--){
        scanf("%d", &n);
        FOR(i, 1, n+1){
            scanf("%d", &a[i]);
        }
        dp[n] = a[n];
        for(int i = n - 1;i >= 1; i--){
            dp[i] = a[i];
            int d;
            if((n-i) < 6) d = n-i;
            else d = 6;
            for(int j = 1;j <= d; j++){
                dp[i] += dp[i+j] / d;
            }
        }
        printf("Case %d: ", cnt++);
        printf("%.10lf\n", dp[1]);
    }
    return 0;
}


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