0
点赞
收藏
分享

微信扫一扫

poj 1741 tree

M4Y 2023-03-26 阅读 36



Tree

Time Limit: 1000MS

 

Memory Limit: 30000K

Total Submissions: 22255

 

Accepted: 7328


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. 


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. 


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


Source


LouTiancheng@POJ



【分析】

点分治

题解传送门





【代码】

//poj 1741 tree 
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=10005;
bool vis[mxn];
int n,m,T,mn,cnt,ans,num,root;
int head[mxn],dis[mxn],size[mxn],mx[mxn];  //mx:以u为根的子树中的最大size 
struct edge {int to,w,next;} f[mxn<<1];
inline void add(int u,int v,int w)
{
	f[++cnt].to=v,f[cnt].w=w,f[cnt].next=head[u],head[u]=cnt;
}
inline void dfssize(int u,int fa)
{
	size[u]=1,mx[u]=0;
	for(int i=head[u];i;i=f[i].next)
	{
		int v=f[i].to;
		if(vis[v] || v==fa) continue;
		dfssize(v,u);
		size[u]+=size[v];
		mx[u]=max(mx[u],size[v]);
	}
}
inline void dfsroot(int r,int u,int fa)
{
	mx[u]=max(mx[u],size[r]-size[u]);
	if(mx[u]<mn) mn=mx[u],root=u;
	for(int i=head[u];i;i=f[i].next)
	{
		int v=f[i].to;
		if(vis[v] || v==fa) continue;
		dfsroot(r,v,u);
	}
}
inline void dfsdis(int w,int u,int fa)
{
	dis[++num]=w;
	for(int i=head[u];i;i=f[i].next)
	{
		int v=f[i].to;
		if(vis[v] || v==fa) continue;
		dfsdis(w+f[i].w,v,u);
	}
}
inline int calc(int u,int d)
{
	int res=0;
	num=0;
	dfsdis(d,u,0);
	sort(dis+1,dis+num+1);
	int i=1,j=num;
	while(i<j)
	{
		while(dis[i]+dis[j]>m && j>i) j--;
		res+=j-i;
		i++;
	}
	return res;
}
inline void dfs(int u)
{
	mn=n;
	dfssize(u,0);
	dfsroot(u,u,0);
	ans+=calc(root,0);
	vis[root]=1;
	for(int i=head[root];i;i=f[i].next)
	{
		int v=f[i].to;
		if(vis[v]) continue;
		ans-=calc(v,f[i].w);
		dfs(v);
	}
}
int main()
{
	int i,j,u,v,w;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		if(!n && !m) return 0;
		M(head),M(vis),cnt=ans=0;
		fo(i,2,n)
		{
			scanf("%d%d%d",&u,&v,&w);
			add(u,v,w),add(v,u,w);
		}
		dfs(1);
		printf("%d\n",ans);
	}
	return 0;
}
/*
5 4
1 2 3
1 3 1
1 4 2
3 5 1
0 0
*/



举报

相关推荐

0 条评论