*【CodeForces - 280C】Game on Tree(期望模型,期望的线性性)
題干:
Momiji has got a rooted tree, consisting of?n?nodes. The tree nodes are numbered by integers from?1?to?n. The root has number?1. Momiji decided to play a game on this tree.
The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by?v) and removes all the subtree nodes with the root in node?v?from the tree. Node?v?gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number?1.
Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
Input
The first line contains integer?n?(1?≤?n?≤?105)?— the number of nodes in the tree. The next?n?-?1?lines contain the tree edges. The?i-th line contains integers?ai,?bi(1?≤?ai,?bi?≤?n;?ai?≠?bi)?— the numbers of the nodes that are connected by the?i-th edge.
It is guaranteed that the given graph is a tree.
Output
Print a single real number — the expectation of the number of steps in the described game.
The answer will be considered correct if the absolute or relative error doesn't exceed?10?-?6.
Examples
Input
2 1 2Output
1.50000000000000000000Input
3 1 2 1 3Output
2.00000000000000000000Note
In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are:
1?×?(1?/?2)?+?2?×?(1?/?2)?=?1.5
In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are:
1?×?(1?/?3)?+?(1?+?1.5)?×?(2?/?3)?=?(1?/?3)?+?(5?/?3)?=?2
題目大意:
給一顆n個點有根的樹,每次任意刪一個當前還存在的點,并刪掉其子樹,問刪完整顆樹的刪點次數的數學期望。
解題報告:
琢磨了半天,似懂非懂,先記下來以后再加深理解吧。
考慮等價問題:對于每一個點,假設考慮第i個點,選擇刪第i個點的平均次數 的和。
既然最終第i個點肯定要被刪除的,那么肯定是他和他到根節點這一條鏈上的節點 都可以做到,那么其中假設深度為d,那么選擇這個點的概率就是,那么對所有的點求個和就是答案。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define F first #define S second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int dep[MAX],n; vector<int> vv[MAX]; void dfs(int cur,int fa,int d) {dep[cur] = d;for(int i = 0; i<vv[cur].size(); i++) {if(vv[cur][i] == fa) continue;dfs(vv[cur][i],cur,d+1);} } int main() {cin>>n;for(int a,b,i = 1; i<=n-1; i++) cin>>a>>b,vv[a].pb(b),vv[b].pb(a);dfs(1,-1,1);double ans = 0;for(int i = 1; i<=n; i++) {ans += 1.0/dep[i];}printf("%.10f\n",ans);return 0 ; }?
總結
以上是生活随笔為你收集整理的*【CodeForces - 280C】Game on Tree(期望模型,期望的线性性)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全省前五!湖南男孩考652高分后陪妈妈做
- 下一篇: 深海与章鱼老师