题目:You are in a cave, a deep cave! The cave can be represented by an 1 x N grid. Some cells in the cave might contain gold!
Initially, you are in position 1. In each move, 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 of the cave, you keep throwing the dice again until you get a suitable result. When you reach the Nth position you stop your journey.
Given the information about the cave, you have to find the expected amount of gold you can collect using the procedure described above.
大意:在一个长度为n的横向的山洞里,有很多黄金,一开始你在位置1,你可以通过掷色子确定你的步数,每到一个地方你都可以把那个地方的黄金捡起来。最终你只能到达n点,不可以越界,如果越界,需要重新掷色子。求得到黄金的数学期望。
思路:从后往前遍历,对于每个点i,都是有j点转移过来的,即dp[i]+=dp[j]/temp(j=[i+1,i+6],temp=6);当n-i<6时,则是j=[i+1,n],temp=n-i;temp为概率。
代码:
#include<bits/stdc++.h>
using namespace std;
int a[105];
double dp[105];
int main()
{
int t;
scanf("%d",&t);
for(int j=1;j<=t;j++)
{
memset(dp,0,sizeof(dp));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
dp[i]=(double)a[i];
}
for(int i=n;i>=1;i--)
{
int temp=min(6,n-i);
for(int j=i+1;j<=i+6&&j<=n;j++)
{
dp[i]+=(dp[j]/temp);
}
}
printf("Case %d: %lf\n",j,dp[1]);
}
return 0;
}