#include <bits/stdc++.h>
using namespace std;
vector<int> g[100005];
int f[100005], ff[100005], b[100005], s[100005];
long long int res[100005], mod = 1e9 + 7;
void dfs(int x, int p) {
f[x] = 0; b[x] = p;
s[x] = 1;
for (int w : g[x]) {
if (w == p) continue;
dfs(w, x);
s[x] += s[w];
if (f[w] == 0) f[x] = 1;
}
}
void dfs2(int x, int p) {
int c = 0;
for (int w : g[x]) {
if (w == p) continue;
c += 1 - f[w];
}
c += 1 - ff[x];
for (int w : g[x]) {
if (w == p) continue;
c -= 1 - f[w];
if (c) ff[w] = 1;
c += 1 - f[w];
dfs2(w, x);
}
}
void dfs3(int x, int p, int flag, int z) {
if (flag == 0) {
for (int w : g[x]) {
if (w == p) continue;
dfs3(w, x, 1, z);
}
res[z]++;
}
else {
if (g[x].size() > 2) return;
for (int w : g[x]) {
if (w == p) continue;
dfs3(w, x, 0, z);
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
long long int n, d;
cin >> n >> d;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1, -1);
ff[1] = 1;
dfs2(1, -1);
long long int c = 0, h = 0, k = 0, x, y, cc = 1;
for (int i = 1; i <= n; i++) {
int flag = 0;
for (int w : g[i]) {
if (w == b[i]) continue;
if (f[w] == 0) flag++;
}
if (ff[i] == 0) flag++;
c += flag;
if (flag >= 2) {
k += n;
}
else if (flag == 1) {
for (int w : g[i]) {
if (w == b[i]) continue;
if (f[w] == 0) {
dfs3(w, i, 1, i);
k += n - s[w];
}
}
if (ff[i] == 0) {
dfs3(b[i], i, 1, i);
k += n - s[i];
}
h += res[i];
}
else {
dfs3(i, -1, 0, i);
h += res[i];
}
if (i == 1) x = h, y = k;
}
h %= mod; k %= mod;
//cout << c << " " << h << " " << k << " " << x << " " << y << '\n';
for (int i = d - 1; i > 1; i--) {
cc = cc * n % mod * n % mod;
long long int res = h * c + k * cc;
c = (cc * n - res) % mod;
if (c < 0) c += mod;
}
cout << (x * c + y * cc) % mod;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |