Tree
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 14250 | Accepted: 4625 |
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
Source
题目大意:n,m,n表示这棵树有n个点,后边n-1条边,问有多少个点对,距离大于等于m
ac代码
14792491 | kxh1995 | 1741 | Accepted | 1568K | 204MS | C++ | 1751B | 2015-10-07 22:36:45 |
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define max(a,b) (a>b?a:b)
using namespace std;
#define N 100100
int head[N],cnt,pre[N],sum,son[N],vis[N],deep[N],root,dis[N];
#define INF 0x3f3f3f3f
int n,m,ans;
struct s
{
int u,v,next,w;
}edge[N<<1];
void add(int u,int v,int w)
{
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void get_root(int u,int fa)
{
son[u]=1;
pre[u]=0;
int i;
for(i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==fa||vis[v])
continue;
get_root(v,u);
son[u]+=son[v];
pre[u]=max(pre[u],son[v]);
}
pre[u]=max(pre[u],sum-son[u]);
if(pre[u]<pre[root])
root=u;
}
void get_deep(int u,int fa)
{
deep[++deep[0]]=dis[u];
int i;
for(i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==fa||vis[v])
continue;
dis[v]=dis[u]+edge[i].w;
get_deep(v,u);
}
}
int get_sum(int x,int now)
{
dis[x]=now;
deep[0]=0;
get_deep(x,0);
sort(deep+1,deep+1+deep[0]);
int res=0,l,r;
for(l=1,r=deep[0];l<r;)
{
if(deep[l]+deep[r]<=m)
{
res+=(r-l);
l++;
}
else
r--;
}
return res;
}
void work(int x)
{
ans+=get_sum(x,0);
vis[x]=1;
int i;
for(i=head[x];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(vis[v])
continue;
ans-=get_sum(v,edge[i].w);
sum=son[v];
root=0;
get_root(v,root);
work(root);
}
}
int main()
{
//int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int i;
cnt=0;
if(n==0)
break;
memset(head,-1,sizeof(head));
for(i=1;i<n;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
sum=n;
pre[0]=INF;
memset(vis,0,sizeof(vis));
root=0;
get_root(1,0);
// memset(vis,0,sizeof(vis));
ans=0;
work(root);
printf("%d\n",ans);
}
}