Tree
POJ - 1741shu de dian fen zhi
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 const int maxn = 1e5 + 10; 7 const int inf = 0x3f3f3f3f; 8 int n, k; 9 int rt, snode, ans; 10 int size[maxn], d[maxn], vis[maxn]; 11 int dep[maxn]; 12 int maxson[maxn]; 13 struct Edge{ 14 int v, w, nxt; 15 Edge(int v = 0, int w = 0, int nxt = 0) : v(v), w(w), nxt(nxt) {} 16 }e[maxn<<1]; 17 int head[maxn], cnt; 18 void init(){ 19 cnt = 0; 20 memset(head, -1, sizeof head); 21 } 22 void add(int u, int v, int w){ 23 e[cnt] = Edge(v, w, head[u]); 24 head[u] = cnt++; 25 } 26 27 void getrt(int u, int f){ 28 size[u] = 1; 29 maxson[u] = 0; 30 for(int i = head[u]; ~i; i = e[i].nxt){ 31 int v = e[i].v; 32 if(v == f || vis[v]) continue; 33 getrt(v, u); 34 size[u] += size[v]; 35 maxson[u] = max(maxson[u], size[v]); 36 } 37 maxson[u] = max(maxson[u], snode - size[u]); 38 if(maxson[u] < maxson[rt]) rt = u; 39 } 40 void getdep(int u, int f){ 41 dep[++dep[0]] = d[u]; 42 for(int i = head[u]; ~i; i = e[i].nxt){ 43 int v = e[i].v; 44 if(v == f || vis[v]) continue; 45 d[v] = d[u] + e[i].w; 46 getdep(v, u); 47 } 48 } 49 int cal(int u, int w){ 50 d[u] = w; 51 dep[0] = 0; 52 getdep(u, 0); 53 sort(dep + 1, dep + 1 + dep[0]); 54 int sum = 0; 55 int l = 1, r = dep[0]; 56 while(l < r){ 57 if(dep[l] + dep[r] <= k) { 58 sum += r - l; 59 l++; 60 }else r--; 61 } 62 return sum; 63 } 64 65 void solve(int u){ 66 vis[u] = 1; 67 ans += cal(u, 0); 68 for(int i = head[u]; ~i; i = e[i].nxt){ 69 int v = e[i].v; 70 if(vis[v]) continue; 71 ans -= cal(v, e[i].w); 72 rt = 0; 73 snode = size[v]; 74 getrt(v, u); 75 solve(rt); 76 } 77 } 78 79 int main(){ 80 while(scanf("%d %d", &n, &k) && (n || k)){ 81 init(); 82 memset(vis, 0, sizeof vis); 83 int u, v, w; 84 for(int i = 1; i < n; i++){ 85 scanf("%d %d %d", &u, &v, &w); 86 add(u, v, w); 87 add(v, u, w); 88 } 89 rt = ans = 0; 90 snode = n; 91 maxson[0] = inf; 92 getrt(1, 0); 93 solve(rt); 94 printf("%d\n", ans); 95 } 96 97 }