路径长小于k的个数,裸题。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdio>
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define RepE(i, x) for (int i = pos[x]; i; i = g[i].nex)
#define Dwn(i, x, y) for (int i = x; i >= y; i --)
using namespace std;
typedef long long LL;
const int N = 10005;
struct arr { int y, nex, l; } g[N*2];
int n, m, ans, pos[N], f[N], s[N], rt, d[N], dz, sz, siz;
bool don[N];
void Init(int x, int y, int z) { g[++ sz] = (arr) { y, pos[x], z }, pos[x] = sz; }
void Get(int x, int fa) {
s[x] = 1, f[x] = 0;
RepE(i, x) {
int y = g[i].y;
if (y == fa || don[y]) continue ;
Get(y, x), s[x] += s[y];
f[x] = max(f[x], s[y]);
}
f[x] = max(f[x], siz - s[x]);
if (f[x] < f[rt]) rt = x;
}
void Dfs(int x, int fa, int z) {
d[++ dz] = z;
int y;
RepE(i, x)
if ((y = g[i].y) != fa && !don[y]){
Dfs(y, x, z + g[i].l);
}
}
int Calc(int x, int st) {
int ret = 0;
dz = 0, Dfs(x, 0, st);
sort(d+1, d+dz+1);
int r = dz;
Rep(i, 1, dz) {
while (r && d[i] + d[r] > m) r --;
if (i > r) break ;
ret += r - i + 1;
}
return ret;
}
void Work(int x) {
ans += Calc(x, 0);
don[x] = 1;
RepE(i, x) {
int y = g[i].y;
if (don[y]) continue ;
ans -= Calc(y, g[i].l);
siz = s[y];
Get(y, rt = 0);
Work(rt);
}
}
int main()
{
for (; scanf("%d%d", &n, &m), n != 0;) {
memset(don, 0, sizeof(don));
memset(pos, 0, sizeof(pos));
sz = 0, ans = 0;
Rep (i, 1, n-1) {
int x, y, z;
scanf ("%d%d%d", &x, &y, &z);
Init(x, y, z);
Init(y, x, z);
}
f[0] = siz = n;
Get(1, rt = 0);
Work(rt);
printf ("%d\n", ans - n);
}
return 0;
}