P3830 [SHOI2012]隨機樹(期望概率,二叉樹套路列舉左右子樹dp,期望轉概率求和)
阿新 • • 發佈:2020-12-07
技術標籤:基礎數論
題意:有n個葉結點的二叉樹,初始時只有一個根,每次等概率的從葉子結點中選一個岔開來。1.求葉子結點平均深度的期望2.樹深度的期望分,定義根節點的深度為0。
分析與總結:對於操作1比較好想,設
f
(
x
−
1
)
f_(x-1)
f(x−1)是有x-1個葉子結點時的平均深度的期望。那麼
f
(
x
)
=
(
f
(
x
−
1
)
∗
(
x
−
1
)
+
f
(
x
−
1
)
+
2
)
/
x
f(x)=(f(x-1)*(x-1)+f(x-1)+2)/x
f(x)=(f(x−1)∗(x−1)+f(x−1)+2)/x,這個建議畫圖很快就能理解。發現每次的增量是f(x-1)+2。對於操作2,又要用到期望轉概率求和
![在這裡插入圖片描述](https://img.796t.com/res/2020/12-07/14/3c6f81b931efabad54dc3d296fb511c7.png)
設 f [ i ] [ j ] f[i][j] f[i][j]為有i個葉結點時樹深度大於等j的概率,那麼根據二叉樹經典套路可以去列舉左右子樹中葉子結點的個數。顯然可以得到方程 f [ i ] [ j ] + = f [ k ] [ j − 1 ] + f [ i − k ] [ j − 1 ] − f [ i − k ] [ j − 1 ] ∗ f [ k ] [ ] j − 1 ] f[i][j]+=f[k][j-1]+f[i-k][j-1]-f[i-k][j-1]*f[k][]j-1] f[i][j]+=f[k][j−1]+f[i−k][j−1]−f[i−k][j−1]∗f[k][]j
#include<bits/stdc++.h>
#define f(i,a,b) for( int i=a;i<=b;++i)
#define ff(i,a,b) for( int i=a;i>=b;--i)
#define debug(x) cerr << #x << " : " << x << " " << endl
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
const ll mod = 1e9 + 7;
const ll mod2 = 998244353;
const int inf = 0x3f3f3f3f;
const double tiaohe = 0.57721566490153286060651209;
ll oula(ll x) { ll res = x;f(i, 2, x / i) { if (x % i == 0) { res = res / i * (i - 1);while (x % i == 0) x /= i; } }if (x > 1) res = res / x * (x - 1);return res; }
ll quickmod(ll a, ll n, ll m) { ll s = 1;while (n) { if (n & 1) { s = s * a % m; }a = (a*a) % m;n = n / 2; }return s; }
ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
void ex_gcd(ll a, ll b, ll &x, ll &y, ll &d) { if (!b) { d = a, x = 1, y = 0; } else { ex_gcd(b, a % b, y, x, d);y -= x * (a / b); } }
ll inv(ll t, ll p) { ll d, x, y;ex_gcd(t, p, x, y, d);return d == 1 ? (x % p + p) % p : -1; }
bool isPrime(ll x) { if (x == 2)return true;if (x % 2 == 0)return false;for (ll i = 2;i*i <= x;i++) if (x % i == 0)return false; return true; }
inline int in() { char ch = getchar();int x = 0, f = 1;while (ch<'0' || ch>'9') { if (ch == '-')f = -1;ch = getchar(); }while (ch >= '0'&&ch <= '9') { x = x * 10 + ch - '0';ch = getchar(); }return x * f; }
//double a = log(n) +tiaohe + 1.0 / (2 * n);
double eqa = (1 + sqrt(5.0)) / 2.0;
double E = 2.7182818284;
const double eps = 1e-6;
const int N = 105;
double dp[N];//葉子節點平均深度
double f[N][N];//有i個節點時樹深度>=j的概率
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
//經典概率論與數理統計
int q, n;cin >> q >> n;
dp[1] = 0;
f(i, 2, n)dp[i] = dp[i - 1] + 2.0 / i;
f(i, 1, n)f[i][0] = 1;
f(i, 2, n)
{
f(j, 1, i - 1)//深度
{
f(k, 1, i - 1)//列舉左右子樹
{
f[i][j] += (f[k][j - 1] + f[i - k][j - 1] - f[k][j - 1] * f[i - k][j - 1]);
}
f[i][j] = f[i][j] / (i - 1);
}
}
double res = 0.0;
f(i, 1, n - 1)res += f[n][i];
if (q == 1) {
printf("%.6lf\n", dp[n]);
}
else printf("%.6lf\n", res);
return 0;
}