1468: Tree
Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 1351 Solved: 713
[ Submit][ Status][ Discuss]
Description
给你一棵TREE,以及这棵树上边的距离.问有多少对点它们两者间的距离小于等于K
Input
N(n<=40000) 接下来n-1行边描述管道,按照题目中写的输入 接下来是k
Output
一行,有多少对点之间的距离小于等于k
Sample Input
7
1 6 13
6 3 9
3 5 7
4 1 3
2 4 20
4 7 2
10
1 6 13
6 3 9
3 5 7
4 1 3
2 4 20
4 7 2
10
Sample Output
5
HINT
Source
题解:点分治
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#define N 100003
using namespace std;
int n,m,tot,point[N],next[N],v[N],len[N];
int d[N],deep[N],son[N],ans,k,sum,root,f[N],vis[N];
void add(int x,int y,int z)
{
tot++; next[tot]=point[x]; point[x]=tot; v[tot]=y; len[tot]=z;
tot++; next[tot]=point[y]; point[y]=tot; v[tot]=x; len[tot]=z;
}
void getroot(int x,int fa)
{
f[x]=0; son[x]=1;
for(int i=point[x];i;i=next[i]){
if (vis[v[i]]||v[i]==fa) continue;
getroot(v[i],x);
son[x]+=son[v[i]];
f[x]=max(f[x],son[v[i]]);
}
f[x]=max(f[x],sum-son[x]);
if (f[x]<f[root]) root=x;
}
void getdeep(int x,int fa)
{
deep[++deep[0]]=d[x];
for (int i=point[x];i;i=next[i]){
if (vis[v[i]]||v[i]==fa) continue;
d[v[i]]=d[x]+len[i];
getdeep(v[i],x);
}
}
int calc(int x,int now)
{
d[x]=now; deep[0]=0;
getdeep(x,0);
sort(deep+1,deep+deep[0]+1);
int l=1; int r=deep[0];
int t=0;
while (l<r) {
if (deep[l]+deep[r]<=k) t+=r-l,l++;
else r--;
}
return t;
}
void work(int x)
{
ans+=calc(x,0);
vis[x]=1;
for (int i=point[x];i;i=next[i]){
if (vis[v[i]]) continue;
ans-=calc(v[i],len[i]);
sum=son[v[i]]; root=0;
getroot(v[i],x);
work(root);
}
}
int main()
{
freopen("a.in","r",stdin);
scanf("%d",&n);
for (int i=1;i<n;i++) {
int x,y,z; scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
}
scanf("%d",&k);
sum=n; f[0]=1000000000; root=0;
getroot(1,0);
work(root);
printf("%d\n",ans);
}