当前位置:网站首页>[problem solving] [show2012] random tree

[problem solving] [show2012] random tree

2022-04-23 16:52:00 Ants looking up at the stars

probability / expect dp Basic questions .

There is a binary tree background .

There are two things worth learning about this problem trick .

First look at the first question . Suppose there is i − 1 i-1 i1 Leaf node , The average depth of each node is f i − 1 f_{i-1} fi1 .

Then randomly select a node to copy . The expected depth of this node is f i − 1 f_{i-1} fi1

therefore f i = ( i − 1 ) f i − 1 + f i − 1 + 2 i = f i − 1 + 2 i f_{i}=\frac{(i-1)f_{i-1}+f_{i-1}+2}{i}=f_{i-1}+\frac{2}{i} fi=i(i1)fi1+fi1+2=fi1+i2

Let's look at the second question .

set up g [ i ] [ j ] g[i][j] g[i][j] Express i i i Second expansion , The depth of the final tree ≥ j \geq j j Of probability .

So the expected depth of the tree ∑ i = 1 n − 1 g [ n − 1 ] [ i ] \sum_{i=1}^{n-1}g[n-1][i] i=1n1g[n1][i]

The total number of schemes observed is ( i − 1 ) ! (i-1)! (i1)! , If the left subtree k k k Time , Right subtree i − k − 1 i-k-1 ik1 Time , that p = k ! ( i − k − 1 ) ! ( i − 1 k ) i ! = 1 i p=\frac{k!(i-k-1)!\binom{i-1}{k}}{i!}=\frac{1}{i} p=i!k!(ik1)!(ki1)=i1 .

So according to probability / The expectation formula , g [ i ] [ j ] = ∑ k = 0 i − 1 g [ k ] [ j ] + g [ i − k − 1 ] [ j ] − g [ k ] [ j ] ∗ g [ i − k − 1 ] [ j ] i g[i][j]=\frac{\sum_{k=0}^{i-1}g[k][j]+g[i-k-1][j]-g[k][j]*g[i-k-1][j]}{i} g[i][j]=ik=0i1g[k][j]+g[ik1][j]g[k][j]g[ik1][j]

Time complexity O ( n 3 ) O(n^3) O(n3) .

#include<bits/stdc++.h>
#define db double
using namespace std;
const int N=105;
db dp[N],dp2[N][N];
int n,Q;
int main() {
    
	for(int i=1;i<=100;i++) {
    
		dp[i]=dp[i-1]+2.0/(i+1);
	}
	for(int i=0;i<=100;i++) dp2[i][0]=1;
	for(int i=1;i<=100;i++) {
    
		for(int j=1;j<=i;j++) {
    
			for(int k=0;k<i;k++) {
    
				dp2[i][j]+=(dp2[k][j-1]+dp2[i-k-1][j-1]-dp2[k][j-1]*dp2[i-k-1][j-1])/i;
			}
		}
	}
	scanf("%d%d",&Q,&n);
	if(Q==1) printf("%lf",dp[n-1]);
	else {
    
		db res=0;
		for(int i=1;i<=n-1;i++) {
    
			res+=dp2[n-1][i];
		}
		printf("%lf",res);
	}
}

版权声明
本文为[Ants looking up at the stars]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231649165891.html