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
題目大意:一共有n個格子,1~n的格子中分別有著不同數量的黃金,最初時,你位于第一個格子,而且你有一個骰子,每次擲出的數字x的概率是相同的,然后你會前進x步到達一個新格子,并且拿掉新格子中的黃金,如果你擲出骰子后將要跳出所有格子,你必須重新擲骰子,直到到達n位置這個格子(即最后一個格子),問拿走金子的期望值是多少,
思路:很顯然,我們在第i個位置,擲出骰子后最多能走到loc=min(i+6,n);所以我們不難得知,我們在第i個位置時期望的公式,我們設len是在第i位置時最多能走的步數 len(i)=min(n-i,6);所以E(i)=E(i+1)/len(i)+E(i+2)/len+E(i+3)/len+…+E(loc)/len(注意這里需要考慮i+6>n的情況);所以我們可以倒著推出E(1),E(1)就是答案,那為什么不能用Ei=E(i-1)/6+E(i-2)/6+E(i-3)/6+E(i-4)/6+E(i-5)/6+E(i-6)/6進行計算呢?我說不行就是不行!! 因為題目要求是從1開始的,這樣不一定滿足從1開始的條件,
可以解釋樣例一下樣例三,3 6 9三個數,從最后開始算起,E(3)=9,E(2)=6+9/1=15,E(1)=3+15/2+9/2=15,E(1)為15即為答案,
上代碼(寫的很丑啊!!! )
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+7;
const int mod=1e9+7;
ll m,n,i,j;
double dp[maxn];
double a[maxn];
int main()
{
ll t,k;
cin>>t;
for(k=1;k<=t;k++)
{
memset(dp,0,sizeof(dp));
cin>>n;
for(ll i=1;i<=n;i++)
{
cin>>a[i];
}
dp[n]=a[n];
for(ll i=n-1;i>=1;i--)
{
dp[i]+=a[i];
ll len=min(n-i,6*1ll);
for(ll j=i+1;j<=min(i+6,n);j++)
dp[i]+=dp[j]/len;
}
printf("Case %lld: ",k);
printf("%.8lf\n",dp[1]);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/200811.html
標籤:其他
上一篇:LeetCode 49字母異位詞分組&50pow(x,n)&51八皇后
下一篇:約瑟夫環
