跳到正文

个人记录

概率期望DP

AsunderSquall约 28 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 28 分钟

版本

  1. v1当前

数学期望

数学期望值Exp=∑i=1n(pi×fi)Exp=\sum_{i=1}^{n} (p_i \times f_i) 其中pip_i表示事件发生的概率,fif_i表示事件的关键值


举例:抛一个公平硬币,问第一次得到正面的投掷次数期望值ExpExp

我们知道,若某次投掷第一次得到正面的投掷次数为ii,则说明前i−1i-1次抛硬币都是反面,第i+1i+1次是正面。这样的概率为12i\frac{1}{2^{i}},而“投掷次数”这个关键值为ii

那么,Exp=∑i=1∞i2iExp=\sum_{i=1}^{\infty}\frac{i}{2^i}

             Exp=12+24+38+416+532+664...+n2n+...\ \ \ \ \ \ \ \ \ \ \ \ \ Exp=\frac 1 2 + \frac 2 4 + \frac 3 8 +\frac 4 {16} +\frac 5 {32} + \frac 6 {64}...+\frac n {2^n} +...

Exp∗2=11+22+34+48+516+632+754...+n+12n+...Exp*2=\frac 1 1+\frac 2 2 +\frac 3 4 +\frac 4 8 + \frac 5 {16}+ \frac 6 {32} + \frac 7 {54}...+ \frac {n+1} {2^n}+...

下式减去上式,得 Exp=1+12+14+18+...=2Exp=1+ \frac 1 2 + \frac 1 4 + \frac 1 8+...=2

结束,是不是很简单?


概率期望DP

一般这种题目会给你一种操作,每次操作会有不同的概率pip_i发生一个事件,从而使当前状态发生变化,最后求状态满足某个条件的期望操作次数或经历几次操作后状态的期望值。

这种题可以用DP来做。


例题A-SGU 495-Kids and Prizes

ICPC (International Cardboard Producing Company) is in the business of producing cardboard boxes. Recently the company organized a contest for kids for the best design of a cardboard box and selected M winners. There are N prizes for the winners, each one carefully packed in a cardboard box (made by the ICPC, of course). The awarding process will be as follows:

  • All the boxes with prizes will be stored in a separate room.
  • The winners will enter the room, one at a time.
  • Each winner selects one of the boxes.
  • The selected box is opened by a representative of the organizing committee.
  • If the box contains a prize, the winner takes it.
  • If the box is empty (because the same box has already been selected by one or more previous winners), the winner will instead get a certificate printed on a sheet of excellent cardboard (made by ICPC, of course).
  • Whether there is a prize or not, the box is re-sealed and returned to the room.

The management of the company would like to know how many prizes will be given by the above process. It is assumed that each winner picks a box at random and that all boxes are equally likely to be picked. Compute the mathematical expectation of the number of prizes given (the certificates are not counted as prizes, of course).

Input The first and only line of the input file contains the values of NN and MM ( 1≤N,M≤100 0001 \leq N,M \leq 100\ 000).

Output The first and only line of the output file should contain a single real number: the expected number of prizes given out. The answer is accepted as correct if either the absolute or the relative error is less than or equal to 10−910^{-9}.

Example(s)

Input 1

代码
5 7

Output 1

代码
3.951424

Input 2

代码
4 3

Output 2

代码
2.3125

题目大意

有nn个盒子,mm个人,每个盒子里有一个礼物,每个人选择一个盒子,如果盒子里有礼物就把它拿出来,每个人选择完后将盒子恢复原样,问最终取出礼物数量的期望值。


题解

设dpidp_i为第ii个人取到礼物的概率。

我们发现,如果第i−1i-1个人取到了礼物,那么第ii个人取到礼物的概率就又少了1n\frac 1 n ,如果没有取到,那么第ii个人取到的概率与第i−1i-1个人相同

状态转移方程:

dpi=dpi−1∗(dpi−1−1n)+(1−dpi−1)×dpi−1dp_i=dp_{i-1}*(dp_{i-1}- \frac 1 n)+ (1-dp_{i-1})\times dp_{i-1}

最终ans=∑i=1mdpians=\sum_{i=1}^{m} dp_i


代码

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
double dp[N];
double ans;
int main()
{
	int n,m;
    	cin>>n>>m;
	dp[1]=1;
	ans=1;
	for(int i=2;i<=m;i++)
	{
		dp[i]+=dp[i-1]*(dp[i-1]-1.0/n);
		dp[i]+=(1-dp[i-1])*dp[i-1];
		ans+=dp[i];
	}
	printf("%.12f\n",ans);
}
## 例题B-ZOJ 3640-Help Me Escape **Background** *If thou doest well, shalt thou not be accepted? and if thou doest not well, sin lieth at the door. And unto thee shall be his desire, and thou shalt rule over him.* *And Cain talked with Abel his brother: and it came to pass, when they were in the field, that Cain rose up against Abel his brother, and slew him.* *And the LORD said unto Cain, Where is Abel thy brother? And he said, I know not: Am I my brother's keeper?* *And he said, What hast thou done? the voice of thy brother's blood crieth unto me from the ground.* *And now art thou cursed from the earth, which hath opened her mouth to receive thy brother's blood from thy hand;* *When thou tillest the ground, it shall not henceforth yield unto thee her strength; a fugitive and a vagabond shalt thou be in the earth.* *—— Bible Chapter 4* Now Cain is unexpectedly trapped in a cave with $N$ paths. Due to LORD's punishment, all the paths are zigzag and dangerous. The difficulty of the ith path is $c_i$. Then we define f as the fighting capacity of Cain. Every day, Cain will be sent to one of the $N$ paths randomly. Suppose Cain is in front of the ith path. He can successfully take $t_i$ days to escape from the cave as long as his fighting capacity $f$ is larger than $c_i$. Otherwise, he has to keep trying day after day. However, if Cain failed to escape, his fighting capacity would increase $c_i$ as the result of actual combat. (A kindly reminder: Cain will never died.) As for $t_i$, we can easily draw a conclusion that $t_i$ is closely related to $c_i)$. Let's use the following function to describe their relationship: $$t_i=\lfloor \frac {1+\sqrt 5} 2 \times c_i\rfloor$$ After $D$ days, Cain finally escapes from the cave. Please output the expectation of $D$. **Input** The input consists of several cases. In each case, two positive integers $N$ and $f$ ($n \leq 100$, $f \leq 10000$) are given in the first line. The second line includes N positive integers $c_i$ ($c_i \leq 10000, 1 \leq i \leq N$) **Output** For each case, you should output the expectation($3$ digits after the decimal point). **Example(s)** **Input** ``` 3 1 1 2 3 ``` **Output** ``` 6.889 ``` -------- ### 题目大意 有一个人被困在一个有$n$个小路的山洞中,每条路有一个难度值$c_i$。这个人有武力值$f$。每天这个人随机选择一条路,如果$f > c_i$ 则他花$t_i$时间逃出,否则武力值增加$c_i$ 。 问需要逃出的天数期望。 --------------------- ### 题解 首先为了表示方便,我们预处理出$t_i$ ```cpp for(int i=1;i<=n;i++) t[i]=floor((1+sqrt(5))*0.5*c[i]*c[i]); ``` 注意到$n \leq 100,f \leq 10000$,那我们可以用$O(nf)$的时间复杂度的算法。 令$dp_{i}$为当前武力值为$i$时的期望逃出天数。 那么他有$\frac 1 n$的概率选择第$j$条路 如果$i>c_j$ 那么此时他还需要的天数期望即为$t_j$,否则为$dp_{i+c_j}+1$ 那么可以写出状态转移方程 ```cpp double p=0; for(int j=1;j<=n;j++) { if(i>c[j])p+=t[j]; else p+=1+dp[i+c[j]]; } dp[i]=p/n; ``` -------------------- ### 代码 ```cpp #include<iostream> #include <cstdio> #include <cmath> using namespace std; const int N=2e4+5; double t[105]; int c[105]; double dp[N]; int main() { int n,f; while(cin>>n>>f) { int mx=f; for(int i=1;i<=n;i++) cin>>c[i]; for(int i=1;i<=n;i++) t[i]=floor((1+sqrt(5))*0.5*c[i]*c[i]); for(int i=N;i>=f;i--) { double p=0; for(int j=1;j<=n;j++) { if(i>c[j])p+=t[j]; else p+=1+dp[i+c[j]]; } dp[i]=p/n; } printf("%.3lf\n",dp[f]); } } ```

例题C-CodeForces 601C-Kleofáš and the nn-thlon

Kleofáš is participating in an nn-thlon - a tournament consisting of nn different competitions in nn different disciplines (numbered 11 through nn). There are mm participants in the nn-thlon and each of them participates in all competitions.

In each of these nn competitions, the participants are given ranks from 11 to mm in such a way that no two participants are given the same rank - in other words, the ranks in each competition form a permutation of numbers from 11 to mm. The score of a participant in a competition is equal to his/her rank in it.

The overall score of each participant is computed as the sum of that participant’s scores in all competitions.

The overall rank of each participant is equal to 1+k1+k, where kk is the number of participants with strictly smaller overall score.

The nn-thlon is over now, but the results haven’t been published yet. Kleofáš still remembers his ranks in each particular competition; however, he doesn’t remember anything about how well the other participants did. Therefore, Kleofáš would like to know his expected overall rank.

All competitors are equally good at each discipline, so all rankings (permutations of ranks of everyone except Kleofáš) in each competition are equiprobable.

Input The first line of the input contains two space-separated integers nn (1≤n≤1001≤n≤100) and mm (1≤m≤10001≤m≤1000) — the number of competitions and the number of participants respectively.

Then, n lines follow. The i-th of them contains one integer xix_i (1≤xi≤m1≤x_i≤m) — the rank of Kleofáš in the ii-th competition.

Output Output a single real number – the expected overall rank of Kleofáš. Your answer will be considered correct if its relative or absolute error doesn’t exceed 10−910^{-9}.

Namely: let’s assume that your answer is aa, and the answer of the jury is bb. The checker program will consider your answer correct, if ∣a−b∣max(1,b)≤10−9\frac{|a-b|} {max(1,b)}\leq 10^{-9}.

Example(s) Input 1

代码
4 10
2
1
2
1

Output 1

代码
1.0000000000000000

Input 2

代码
5 5
1
2
3
4
5

Output 2

代码
2.7500000000000000

Input 3

代码
3 6
2
4
2

Output 3

代码
1.6799999999999999

题目大意

奇怪的比赛名称 有mm个人参加比赛,比赛分为nn场,每场比赛每个人会获得一个唯一的排名。最终得分为所有排名相加。得分越小总排名越考前。现在已知一个人的每场比赛排名,第ii场的排名为cic_i,问总排名的期望值。


题解

设这个人总得分为tottot(随你怎么叫)

直接算比较难,我们可以计算比这个人得分更少的概率。

算出任意一个人总共拿jj分的概率。

求出(∑j=ntot−1pj)∗(m−1)(\sum_{j=n}^{tot-1} p_j)*(m-1)即可


设dpi,jdp_{i,j}为前ii场比赛拿jj分的概率

对于一般的情况

设LL为当到第ii场共有jj分时,到第i−1i-1场至少要有的分 同理,设RR为当到第ii场共有jj分时,到第i−1i-1场最多要有的分 为了表示方便,再设dd为任意一场拿到任意一个排名(除了cic_i)的概率

L=j−m,R=(i−1)∗m,d=1m−1L=j-m,R=(i-1)*m,d=\dfrac{1}{m-1} dpi,j=∑k=LRdpi−1,k∗ddp_{i,j}=\sum_{k=L}^{R}dp_{i-1,k}*d

但是这样会超时 考虑处理前缀和

sumi,j=∑k=1jdpi,ksum_{i,j}=\sum_{k=1}^jdp_{i,k}

则

dpi,j=sumi−1,R−sumi−1,Ldp_{i,j}=sum_{i-1,R}-sum_{i-1,L}

再考虑特殊情况:如果在边界上就修改LL或RR,如果L≤j−ci≤RL\leq j-c_i \leq R则减去这一种情况

C++
d=1.0/(m-1);
dp[0][0]=sum[0]=1;
for(int i=1;i<=n;i++)
{
	for(int j=i;j<=i*m;j++)
	{
		L=max(i-1,j-m),R=min((i-1)*m,j-1);
		dp[i][j]=d*sum[R];
		if(L)dp[i][j]-=d*sum[L-1];
		if(L<=j-c[i]&&j-c[i]<=R) dp[i][j]-=d*dp[i-1][j-c[i]];
	}
	for(int j=1;j<=i*m;j++)sum[j]=sum[j-1]+dp[i][j];
}
for(int j=n;j<tot;j++) ans+=dp[n][j];
printf("%.12lf\n",ans*(m-1)+1);

代码

C++
#include<bits/stdc++.h>
using namespace std;
const int N=105;
const int M=1005;
int n,m,my_pts,L,R;
int c[N];
double d,ans;
double dp[N][N*M],sum[N*M];
//dp[i][j]表示前i场比赛获得j分的概率
int main()
{
	cin>>n>>m;
	d=1.0/(m-1);
	for(int i=1;i<=n;i++) cin>>c[i],my_pts+=c[i];
	dp[0][0]=sum[0]=1;
	for(int i=1;i<=n;i++)
	{
		for(int j=i;j<=i*m;j++)
		{
			L=max(i-1,j-m),R=min((i-1)*m,j-1);
			dp[i][j]=d*sum[R];
			if(L)dp[i][j]-=d*sum[L-1];
			if(L<=j-c[i]&&j-c[i]<=R)
				dp[i][j]-=d*dp[i-1][j-c[i]];
		}
		for(int j=1;j<=i*m;j++)sum[j]=sum[j-1]+dp[i][j];
	}

	for(int j=n;j<my_pts;j++)ans+=dp[n][j];
	printf("%.12lf\n",ans*(m-1)+1);
}
## 例题D-ZOJ 3329-One Person Game There is a very simple and interesting one-person game. You have $3$ dice, namely ****Die1****, ****Die2**** and ****Die3****. ****Die1**** has $K_1$ faces. **Die2** has $K_2$ faces. **Die3** has $K_3$ faces. All the dice are fair dice, so the probability of rolling each value, $1$ to $K_1$, $K_2$, $K_3$ is exactly $\frac 1 {K_1}$, $\frac 1 {K_2}$ and $ \frac 1 {K_3}$. You have a counter, and the game is played as follow: - **1.** Set the counter to $0$ at first. - **2.** Roll the $3$ dice simultaneously. If the up-facing number of **Die1** is $a$, the up-facing number of **Die2** is $b$ and the up-facing number of **Die3** is $c$, set the counter to $0$. Otherwise, add the counter by the total value of the $3$ up-facing numbers. - **3.** If the counter's number is still not greater than $n$, go to step $2$. Otherwise the game is ended. Calculate the expectation of the number of times that you cast dice before the end of the game. **Input** There are multiple test cases. The first line of input is an integer $T$ ($0 < T \leq 300$) indicating the number of test cases. Then $T$ test cases follow. Each test case is a line contains $7$ non-negative integers $n,K_1,K_2,K_3, a, b, c$($0 \leq n \leq 500$,$1 < K_1, K_2, K_3 \leq 6$, $1 \leq a <= K_1$,$ 1 <= b <= K_2$,$ 1 <= c <= K_3$). **Output** For each test case, output the answer in a single line. A relative error of $10^{-8}$ will be accepted. **Example(s)** **Input1** ``` 2 0 2 2 2 1 1 1 0 6 6 6 1 1 1 ``` **Output1** ``` 1.142857142857143 1.004651162790698 ``` ### 题目大意 有$3$个骰子,分别能投出$1$~$k_1$、$1$~$k_2$、$1$~$k_3$的数。 现在你要不停地投骰子($3$个一起投),将投到的数字累加记为得分。 特别地,如果投到$3$个骰子的数刚好分别是$a,b,c$,将得分清零。 问使得分$>n$的投骰子次数期望值。 --------- ### 题解 看到数据范围$1\leq k_1,k_2,k_3 \leq 6$ 可以先预处理投到$3$个骰子之和的概率(特别地,$p_0$表示清零的概率) 这段代码: ``` for (int i=1;i<=k1;i++) for (int j=1;j<=k2;j++) for (int k=1;k<=k3;k++) if (!(i==a1 && j==a2 && k==a3)) p[i+j+k]+=1.0/(k1*k2*k3); else p[0]=1.0/(k1*k2*k3); ``` 然后开始推公式 设$f_{i}$为已经有$i$分时期望投掷次数(不要问我为什么上一题是$dp$这一题是$f$,只是我觉得$dp_0$太丑了) $$f_i=\sum_{j=1}^{k_1+k_2+k_3}p_j*f_{i+j} \ +1+ \ p_0*f_0$$ 这个$k_1+k_2+k_3$写成$18$当然也是可以的 ~~完结!撒花!(当然是假的)~~ 注意到递推式中有个$f_0$,而这却正是我们要求的,显然不能直接这么做。 那怎么办? 我们可以把$f_0$看作未知数,再把所有$f_i$都化成$A_i*f_0+B_i$的形式,最后解一个简单的方程即可。 那么,我们有: $$f_i=A_i*p_0+B_i$$ $$A_i*f_0+B_i=\sum_{j=1}^{k_1+k_2+k_3} [p_j*(A_{i+j}*f_0+B_{i+j})]+p_0*f_0+1$$ 分离$A_i$和$B_i$ $$A_i=\sum_{j=1}^{k_1+k_2+k_3}(p_j*A_{i+j})+p_0$$ $$B_i=\sum_{j=1}^{k_1+k_2+k_3}(p_j*B_{i+j})+1$$
C++
for(int i=n;i>=0;i--)
{
	for(int j=1;j<=k1+k2+k3;j++)
	{
		A[i]+=A[i+j]*p[j];
		B[i]+=B[i+j]*p[j];
	}
	A[i]+=p[0];
	B[i]+=1.0;
}

那么最后我们得到了

f0=A0∗f0+B0f_0=A_0*f_0+B_0 f0=B01−A0f_0=\dfrac{B_0}{1-A_0}
代码
printf( "%.12lf\n", B[0]/(1.0-A[0]));

代码

C++
#include<bits/stdc++.h>
using namespace std;
const int N=550,M=1010;
int n;
int k1,k2,k3;
int a1,a2,a3;
double p[19];
double A[N],B[N];
//dp[i]=A[i]*p[0]+B[i]
int main()
{
	int T;
	cin>>T;
	while (T--)
	{
		memset(p,0,sizeof(p));
		memset(A,0,sizeof(A));
		memset(B,0,sizeof(B));
		cin>>n>>k1>>k2>>k3>>a1>>a2>>a3;
		for (int i=1;i<=k1;i++)
			for (int j=1;j<=k2;j++)
				for (int k=1;k<=k3;k++)
					if (!(i==a1 && j==a2 && k==a3))p[i+j+k]+=1.0/(k1*k2*k3); else p[0]=1.0/(k1*k2*k3);
		for(int i=n;i>=0;i--)
		{
			for(int j=1;j<=k1+k2+k3;j++)
			{
				A[i]+=A[i+j]*p[j];
				B[i]+=B[i+j]*p[j];
			}
			A[i]+=p[0];
			B[i]+=1.0;
		}
		printf( "%.12lf\n", B[0]/(1.0-A[0]));
	}
}
原文