Random Access Iterator
Recently Kumiko learns to use containers in C++ standard template library.
She likes to use the std::vector very much. It is very convenient for her to do operations like an ordinary array. However, she is concerned about the random-access iterator use in the std::vector. She misunderstanding its meaning as that a vector will return an element with equal probability in this container when she access some element in it.
As a result, she failed to solve the following problem. Can you help her?You are given a tree consisting of nn vertices, and 11 is the root of this tree. You are asked to calculate the height of it.The height of a tree is defined as the maximum number of vertices on a path from the root to a leaf.Kumiko’s code is like the following pseudo code.She calls this function dfs(1, 1), and outputs the maximum value of depth array.Obviously, her answer is not necessarily correct. Now, she hopes you analyze the result of her code.Specifically, you need to tell Kumiko the probability that her code outputs the correct result.To avoid precision problem, you need to output the answer modulo 10^9 + 7
Input
The first line contains an integer nn - the number of vertices in the tree (2 \le n \le 10^6)(2≤n≤10 6).Each of the next n - 1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers u_iu i and v_iv i
, the indices of vertices it connectsIt is guaranteed that the given edges form a tree.
Output
Print one integer denotes the answer.
题意
给你一个树,从根节点出发,如果有k个子节点,就对子节点做k次随机访问。每次等概率地随机返回其中一个节点,问其中一个最深节点被访问到的概率是多少。
思路
概率dp,维护不能搜到的概率,1-((pro)的子节点数次方)就是答案
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6 + 10;
const ll mod = 1e9 + 7;
vector<int> v[N];
int n;
int maxx, dep[N];
ll dp[N];
void dfs(int u, int fa ) {
dep[u] = dep[fa] + 1;
maxx = max(maxx, dep[u]);
int to;
for(int i = 0; i < v[u].size(); i++) {
to = v[u][i];
if(to == fa) continue;
dfs(to, u);
}
}
ll ksm(ll x, ll y) {
ll res = 1;
while(y) {
if(y & 1) res = res * x % mod;
y >>= 1;
x = x * x % mod;
}
return res;
}
void dfs1(int u, int fa) {
int flag = 0;
ll cnt = 0;
ll len = v[u].size();
if(u != 1) len--;
ll tmp = ksm(len, mod - 2);
ll d;
int to;
for(int i = 0; i < v[u].size(); i++) {
to = v[u][i];
if(to == fa) continue;
dfs1(to, u);
cnt = (cnt + (1 - dp[to] + mod) % mod * tmp % mod) % mod;
flag = 1;
}
if(flag == 0) {
if(dep[u] == maxx)
dp[u] = 1;
} else {
dp[u] = (1 - ksm(cnt, len) % mod + mod) % mod;
}
}
int main() {
scanf("%d", &n);
int x, y;
for(int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
}
dfs(1, 1);
dfs1(1, 1);
printf("%lld\n", dp[1]);
return 0;
}