首页 > 其他 > 详细

Tree POJ - 1741

时间:2018-01-23 13:49:22      阅读:235      评论:0      收藏:0      [点我收藏+]
shu 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 }
View Code

 

Tree POJ - 1741

原文:https://www.cnblogs.com/yijiull/p/8335195.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!