1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include <bits/stdc++.h> #define MAX_N 40000 using namespace std; int n, k, rt, s[MAX_N+5], h[MAX_N+5], d[MAX_N+5], tot, ans; vector <int> G[MAX_N+5], E[MAX_N+5], dep; bool mrk[MAX_N+5]; void addedge(int u, int v, int c) {G[u].push_back(v), E[u].push_back(c);} void getrt(int u, int fa) { s[u] = 1, h[u] = 0; for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i]; if (v == fa || mrk[v]) continue; getrt(v, u), s[u] += s[v], h[u] = max(h[u], s[v]); } h[u] = max(h[u], tot-s[u]); if (h[u] < h[rt]) rt = u; } void getdep(int u, int fa) { dep.push_back(d[u]), s[u] = 1; for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i], c = E[u][i]; if (v == fa || mrk[v]) continue; d[v] = d[u]+c, getdep(v, u), s[u] += s[v]; } } int calc(int u, int init) { dep.clear(), d[u] = init, getdep(u, 0), sort(dep.begin(), dep.end()); int ret = 0; for (int l = 0, r = (int)dep.size()-1; l < r; ) dep[l]+dep[r] <= k ? ret += r-l++ : r--; return ret; } void DFS(int u) { ans += calc(u, 0), mrk[u] = true; for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i], c = E[u][i]; if (mrk[v]) continue; ans -= calc(v, c), h[0] = tot = s[v], getrt(v, rt = 0), DFS(rt); } } int main() { scanf("%d", &n); for (int i = 1, u, v, c; i < n; i++) scanf("%d%d%d", &u, &v, &c), addedge(u, v, c), addedge(v, u, c); scanf("%d", &k); h[0] = tot = n, getrt(1, 0); DFS(rt); printf("%d", ans); return 0; }
|