Discovering Gold--概率dp-期望

ACM专题学习二

题目

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
Case 2: 13.000000
Case 3: 15.0000000000


题意

        在一个1*N的格子里,每个格子都有相应的金币数,走到相应格子的话,就可以得到该格子的金币。 
        现在有一个人在1这个位置,手里有一颗骰子,骰子摇到几,他就前进几步,但有一种情况例外,如果当前位置+骰子数 > N,那么他就会重新摇骰子。 如果走到N位置,意味着游戏结束了。 请问游戏结束时,这个人得到金币的期望值。

思路

当他走到的位置为不大于N-6,他摇出的骰子数有6种,概率都为1/6,如果大于N-6,则摇出的骰子数只有k种(k为从当前位置到终点所需的数),因为他如果摇多了摇就要重新摇,每个数概率都为1/k。我们用dp[i]来存放到i个格子的概率,最后各格子的黄金数乘对应概率,其和就为期望值。

初始化:dp[1]=1;其他值为0。

为了较好的表述能摇出的骰子数,可以把k的取值写成k = min(N-i,6);i为当前位置。

从当前位置摇骰子能摇出k种数,依次给能到达的k个位置增加概率。

	for(int i = 1; i<=n; i++) 
		{
			int k = min(n-i,6); 
			for(int j = 1; j<=k; j++) 
				if(i+j<=n)
				dp[i+j] += dp[i]/k;
		}

代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring> 
using namespace std;
const int MAX = 2e5 + 5;
int n,a[MAX];
double dp[MAX];
int main()
{
	int t,Case=0;
	cin>>t;
	while(t--) 
	{
		scanf("%d",&n);
		for(int i = 1; i<=n; i++) 
		scanf("%d",a+i);
		memset(dp,0,sizeof(dp));
		dp[1]=1;
		for(int i = 1; i<=n; i++) 
		{
			int k = min(n-i,6); 
			for(int j = 1; j<=k; j++) 
				if(i+j<=n)
				dp[i+j] += dp[i]/k;
		}
		double ans = 0;
		printf("Case %d: ",++Case);
		for(int i = 1; i<=n; i++) ans += dp[i] * a[i];
			printf("%.8f\n",ans);
	}
	return 0 ;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值