1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include<cstdio> #include<cstring> #include<cctype> #include<algorithm> using namespace std;
inline int readint(){ int x=0; bool minu=false; char c=getchar(); while(!isdigit(c) && c-'-') c=getchar(); if(c=='-') minu=true; else x=c-'0',c=getchar(); while(isdigit(c)) x=x*10+c-'0',c=getchar(); return minu?-x:x; }
const int inf=~0u>>1; const int maxn=20000; int n,k,ans; int to[maxn],w[maxn],nxt[maxn],cur[maxn],cnt; void insert(int x,int y,int z){ to[cnt]=y,w[cnt]=z,nxt[cnt]=cur[x],cur[x]=cnt++; to[cnt]=x,w[cnt]=z,nxt[cnt]=cur[y],cur[y]=cnt++; }
bool visited[maxn]; bool being[maxn];
int now,bary; int num[maxn]; void find(int u,int sum){ being[u]=true; int mx=0; num[u]=1; for(int i=cur[u];i>=0;i=nxt[i]){ int v=to[i]; if(!being[v] && !visited[v]){ find(v,sum); num[u]+=num[v]; mx=max(mx,num[v]); } } mx=max(mx,sum-num[u]); if(mx<now) now=mx,bary=u; }
int dis[maxn],cnt2; void dfs(int u,int d){ being[u]=true; dis[cnt2++]=d; for(int i=cur[u];i>=0;i=nxt[i]){ int v=to[i]; if(!being[v] && !visited[v]) dfs(v,d+w[i]); } } int calc(int u,int x){ cnt2=0; dfs(u,x); memset(being,0,sizeof(being)); sort(dis,dis+cnt2); int l=0,r=cnt2-1,res=0; while(l<r){ while(dis[l]+dis[r]>k && l<r) r--; res+=r-l++; } return res; }
void work(int u,int sum){ now=inf; bary=u; find(u,sum); memset(being,0,sizeof(being)); visited[bary]=true; ans+=calc(bary,0); for(int i=cur[bary];i>=0;i=nxt[i]){ int v=to[i]; if(!visited[v]){ ans-=calc(v,w[i]); work(v,num[v]); } } }
void init(){ ans=cnt=0; memset(cur,-1,sizeof(cur)); memset(visited,0,sizeof(visited)); } int main(){ while(~scanf("%d%d",&n,&k) && n){ init(); for(int i=1,x,y,z;i<n;i++){ x=readint()-1,y=readint()-1,z=readint(); insert(x,y,z); } work(0,n); printf("%d\n",ans); } return 0; }
|