LightOj-1030 Discovering Gold (期望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
题解:
起始位置是1,从1走到n,给你一个骰子(6个面),按点数走,收集每一点上的金子,如果你将要走到的位置在n之内,就继续扔,往前走,如果在n之外,就一直扔到合适的位置为止,求到达n点时的期望
这个题是一个求期望的题,那么值得注意的是,当扔在n之外的情况是无效的,所以我们在位置i<n−6i<n−6的时候 此时的概率应该为 1/(n-i),当我们在算权值的时候,我们发现对于位置i来说,它可以到i+1,i+2,……,i+6i+1,i+2,……,i+6 这些点,而这些点的权值又与他们后面6个点相关,因此我们倒过来从最后一个点开始求,最后一个点是一定会取的,于是我们就用一个dp数组把他计算一下;
参考代码为:

1 #include<bits/stdc++.h> 2 using namespace std; 3 int T,n; 4 double dp[110]; 5 6 int main() 7 { 8 scanf("%d",&T); 9 for(int k=1;k<=T;k++) 10 { 11 scanf("%d",&n); 12 memset(dp,0,sizeof dp); 13 for(int i=1;i<=n;i++) scanf("%lf",dp+i); 14 for(int i=n-1;i>=1;i--) 15 { 16 for(int j=1;j<=6;j++) dp[i]+=dp[i+j]/(1.0*min(6,n-i)); 17 } 18 printf("Case %d: %.10lf\n",k,dp[1]); 19 } 20 21 return 0; 22 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· 开发的设计和重构,为开发效率服务
· C# - 获取枚举描述 - 使用增量源生成器