Topic Links:
Poj 1741 Tree
This topic tle good bitter Ah, originally has been the center of gravity of the tree did not find the right, tle for a long time, finally to, good moved, first put a code.
1#include <cstdio>2#include <cstring>3#include <iostream>4#include <algorithm>5 using namespacestd;6 7 Const intMAXN =10010;8 structnode9 {Ten intTo , W, next; One}edge[maxn*2]; A intHEAD[MAXN], VIS[MAXN], SIZE[MAXN], MU[MAXN]; - inttot, N, K, ans, root, Mini, D, DIS[MAXN]; - the voidInit () - { -tot = ans =0; -Memset (Head,-1,sizeof(head)); +memset (Vis,0,sizeof(Vis)); - } + voidADD (int from,intTo,intval) A { atEdge[tot].to =to ; -EDGE[TOT].W =Val; -Edge[tot].next = head[ from]; -head[ from] = tot + +; - } - voidDfsroot (intUintfather) in { -Size[u] =1; toMu[u] =0; + for(intI=head[u]; i!=-1; I=edge[i].next) - { the intv =edge[i].to; * if(!vis[v] && v!=father) $ {Panax Notoginseng Dfsroot (V, u); -Size[u] + =Size[v]; theMu[u] =Max (Mu[u], size[v]); + } A } theMu[u] = max (Mu[u], N-Size[u]); + if(Mini >Mu[u]) -Root =u; $ } $ voidDfsdist (intUintFatherintW) - { -Dis[d + +] =W; the for(intI=head[u]; i!=-1; I=edge[i].next) - {Wuyi intv =edge[i].to; the if(!vis[v] && v!=father) -Dfsdist (V, u, w+EDGE[I].W); Wu } - } About intCalc (intUintW) $ { - intres =0; -D =0; -Dfsdist (U,0, W); ASort (DIS, dis+d); + intI=0, j=d-1; the while(I <j) - { $ while(Dis[i] + dis[j] > K && i<j) theJ--; theRes + = J-i; thei + +; the } - returnRes; in } the voidDFS (intu) the { AboutMini =N; theDfsroot (U,0); theAns + = Calc (root,0); theVis[root] =1; + for(intI=head[root]; i!=-1; I=edge[i].next) - { the intv =edge[i].to;Bayi if(!Vis[v]) the { theAns-=Calc (v, EDGE[I].W); - Dfs (v); - } the } the } the intMain () the { - while(SCANF ("%d%d", &n, &k), n+k) the { the init (); the for(intI=1; i<n; i++)94 { the intu, V, W; thescanf (" %d%d%d", &u, &v, &W); the Add (U, V, W);98 Add (V, U, W); About } -DFS (1);101printf ("%d\n", ans);102 }103 return 0;104}
Poj 1741 Tree (partition of the trees)