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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #include <bits/stdc++.h> using namespace std;
const int MAXN = 10005;
struct edge { int v, l; edge(int v_, int l_) : v(v_), l(l_){}; };
vector<edge> g[MAXN]; vector<int> dep; int n, k, dist[MAXN], vis[MAXN], f[MAXN], root, ans, s[MAXN], tot;
inline void getroot(int now, int fa) { int u; s[now] = 1, f[now] = 0; for (int i = 0; i < g[now].size(); i++) { u = g[now][i].v; if (u != fa && !vis[u]) getroot(u, now), s[now] += s[u], f[now] = max(f[now], s[u]); } f[now] = max(f[now], tot - s[now]); if (f[now] < f[root]) root = now; }
inline void getdep(int now, int fa) { int u; dep.push_back(dist[now]), s[now] = 1; for (int i = 0; i < g[now].size(); i++) { u = g[now][i].v; if (u != fa && !vis[u]) dist[u] = dist[now] + g[now][i].l, getdep(u, now), s[now] += s[u]; } }
inline int calc(int now, int len) { dep.clear(), dist[now] = len; getdep(now, 0), sort(dep.begin(), dep.end()); int cnt = 0, l = 0, r = dep.size() - 1; while (l < r) if (dep[l] + dep[r] <= k) cnt += r - l, l++; else r--; return cnt; }
inline void work(int now) { int u; ans += calc(now, 0), vis[now] = true; for (int i = 0; i < g[now].size(); i++) { u = g[now][i].v; if (!vis[u]) ans -= calc(u, g[now][i].l), f[0] = tot = s[u], root = 0, getroot(u, 0), work(root); } }
int main() { while (~scanf("%d%d", &n, &k)) { if (!n && !k) break; for (int i = 0; i <= n; i++) g[i].clear(); memset(vis, 0, sizeof(int) * (n + 1)); int u, v, l; for (int i = 1; i < n; i++) scanf("%d%d%d", &u, &v, &l), g[u].push_back(edge(v, l)), g[v].push_back(edge(u, l)); f[0] = n, root = 0, tot = n; getroot(1, 0), ans = 0, work(root), printf("%d\n", ans); } }
|