树分治入门题。。。树分治介绍和此题的解法国家集训队论文里都有。。。请看这里http://wenku.baidu.com/link?url=zeAfV5y_bqZ4Y_2EzHQpnXcZIhW6yo4ExY55HRwb4GyOwjybwL9EgcIzTYOehKRS_8hnJY7MT2s18kfiqDGApFn7ekHPZS_ZEQN87xP3Rfe
#include <iostream> #include <queue> #include <stack> #include <map> #include <set> #include <bitset> #include <cstdio> #include <algorithm> #include <cstring> #include <climits> #include <cstdlib> #include <cmath> #include <time.h> #define maxn 10005 #define maxm 20005 #define eps 1e-7 #define mod 1000000007 #define INF 0x3f3f3f3f #define PI (acos(-1.0)) #define lowbit(x) (x&(-x)) #define mp make_pair #define ls o<<1 #define rs o<<1 | 1 #define lson o<<1, L, mid #define rson o<<1 | 1, mid+1, R #define pii pair<int, int> #pragma comment(linker, "/STACK:16777216") typedef long long LL; typedef unsigned long long ULL; //typedef int LL; using namespace std; LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;} LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;} //head struct Edge { int v, w; Edge *next; }*H[maxn], *edges, E[maxm]; bool done[maxn]; int size[maxn]; int mx[maxn]; int n, k, root, ans, nsize; vector<int> dis; void addedges(int u, int v, int w) { edges->v = v; edges->w = w; edges->next = H[u]; H[u] = edges++; } void init() { edges = E; memset(H, 0, sizeof H); memset(done, 0, sizeof done); } void read() { int u, v, w; for(int i = 1; i < n; i++) { scanf("%d%d%d", &u, &v, &w); addedges(u, v, w); addedges(v, u, w); } } void getroot(int u, int fa) { mx[u] = 0, size[u] = 1; for(Edge *e = H[u]; e; e = e->next) if(!done[e->v] && e->v != fa) { int v = e->v; getroot(v, u); size[u] += size[v]; mx[u] = max(mx[u], size[v]); } mx[u] = max(mx[u], nsize - size[u]); if(mx[u] < mx[root]) root = u; } void getdis(int u, int fa, int dist) { dis.push_back(dist); for(Edge *e = H[u]; e; e = e->next) if(!done[e->v] && e->v != fa) { int v = e->v, w = e->w; getdis(v, u, dist + w); } } int calc(int u, int dist) { int res = 0; dis.clear(); getdis(u, 0, dist); sort(dis.begin(), dis.end()); for(int l = 0, r = dis.size() - 1; l < r; ) { if(dis[l] + dis[r] <= k) res += r - l++; else r--; } return res; } void solve(int u) { ans += calc(u, 0); done[u] = true; for(Edge *e = H[u]; e; e = e->next) if(!done[e->v]) { int v = e->v, w = e->w; ans -= calc(v, w); mx[0] = nsize = size[v]; getroot(v, root = 0); solve(root); } } void work() { ans = 0; mx[0] = nsize = n; getroot(1, root = 0); solve(root); printf("%d\n", ans); } int main() { while(scanf("%d%d", &n, &k), n != 0 || k != 0) { init(); read(); work(); } return 0; }