Description
Give a tree with n vertices,each edge has a length(positive integer less than 1001).
Define dist(u,v)=The min distance between node u and v.
Give an integer k,for every pair (u,v) of vertices is called valid if and only if dist(u,v) not exceed k.
Write a program that will count how many pairs which are valid for a given tree.
Define dist(u,v)=The min distance between node u and v.
Give an integer k,for every pair (u,v) of vertices is called valid if and only if dist(u,v) not exceed k.
Write a program that will count how many pairs which are valid for a given tree.
Input
The input contains several test cases. The first line of each test case contains two integers n, k. (n<=10000) The following n-1 lines each contains three integers u,v,l, which means there is an edge between node u and v of length l.
The last test case is followed by two zeros.
The last test case is followed by two zeros.
Output
For each test case output the answer on a single line.
Sample Input
5 4
1 2 3
1 3 1
1 4 2
3 5 1
0 0
Sample Output
8
题意:有一棵树,每条边多有一个边权,问你有多少对(u,v)满足dis(u,v)<= k
粘点重心相关知识,与本题无关,树的重心的一些性质:
1.树中所有点到某个点的距离和中,到重心的距离和是最小的;如果有两个重心,那么他们的距离和一样。
2.把两个树通过一条边相连得到一个新的树,那么新的树的重心在连接原来两个树的重心的路径上。
3.把一个树添加或删除一个叶子,那么它的重心最多只移动一条边的距离。
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #define maxn 10010 #define inf 1e8 int p[maxn],num; struct node { int u,v,len,next; node() {} node(int u,int v,int len,int next): u(u),v(v),len(len),next(next) {} }E[maxn*2]; void init() { num=0; memset(p,-1,sizeof(p)); } void add(int u,int v,int len) { E[num]=node(u,v,len,p[u]); p[u]=num++; } int n,k; int ans; int si[maxn],maxx[maxn],dis[maxn]; bool use[maxn]; int root; int mm,cnt; void dfs_size(int u,int fa) { si[u]=1; maxx[u]=0; for(int i=p[u];~i;i=E[i].next) { int v=E[i].v; if(v==fa||use[v]) continue; dfs_size(v,u); si[u]+=si[v]; maxx[u]=max(maxx[u],si[v]); } } void dfs_root(int id,int u,int fa)///找出重心 { if(si[id]-si[u]>maxx[u]) maxx[u]=si[id]-si[u]; if(maxx[u]<mm) { mm=maxx[u]; root=u; } for(int i=p[u];~i;i=E[i].next) { int v=E[i].v; if(v==fa||use[v]) continue; dfs_root(id,v,u); } } void dfs_dis(int u,int fa,int d) { dis[cnt++]=d; for(int i=p[u];~i;i=E[i].next) { int v=E[i].v; int len=E[i].len; if(v==fa||use[v]) continue; dfs_dis(v,u,d+len); } } int get(int u,int d) { cnt=0; dfs_dis(u,-1,d); int res=0; sort(dis,dis+cnt); int l=0,r=cnt-1; while(l<r) { while(dis[l]+dis[r]>k&&l<r) r--; res+=r-l; l++; } return res; } void solve(int u) { dfs_size(u,-1); mm=n; dfs_root(u,u,-1); use[root]=true; ans+=get(root,0); for(int i=p[root];~i;i=E[i].next) { int v=E[i].v; int len=E[i].len; if(use[v]) continue; ans-=get(v,len); solve(v); } } int main() { while(scanf("%d%d",&n,&k),n||k) { init(); for(int i=1;i<n;i++) { int u,v,len; scanf("%d%d%d",&u,&v,&len); add(u,v,len); add(v,u,len); } ans=0; for(int i=1;i<=n;i++) use[i]=false; solve(1); printf("%d\n",ans); } return 0; }