bzoj1468 Tree

时间:2023-03-09 03:19:00
bzoj1468 Tree

最经典的点分治题目,在递归子树的时候减去在算父亲时的不合法方案。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
#define ll long long
#define N 40005
using namespace std;
struct Node{
int to,next,v;
}e[N<<];
int sum,rt,n,k,head[N],tot,cnt,mx[N],sz[N],tmp[N],ans;
bool vis[N];
void add(int x,int y,int z){
e[++tot]=(Node){y,head[x],z};head[x]=tot;
e[++tot]=(Node){x,head[y],z};head[y]=tot;
}
void getroot(int x,int fa){
mx[x]=;sz[x]=;
for(int i=head[x];i;i=e[i].next)if(e[i].to!=fa&&!vis[e[i].to]){
getroot(e[i].to,x);
sz[x]+=sz[e[i].to];
mx[x]=max(mx[x],sz[e[i].to]);
}mx[x]=max(mx[x],sum-sz[x]);
if(mx[x]<mx[rt])rt=x;
}
void getdis(int x,int fa,int d){
tmp[++cnt]=d;
for(int i=head[x];i;i=e[i].next)if(e[i].to!=fa&&!vis[e[i].to]){
getdis(e[i].to,x,d+e[i].v);
}
}
void calc(int x,int dis,int type){
cnt=;
getdis(x,,);
sort(tmp+,tmp++cnt);
int l=,r=cnt;
while(l<=r){
while(tmp[l]+tmp[r]>dis)r--;
if(l>r)break;
ans+=(r-l)*type;l++;
}
}
void work(int x){
vis[x]=;
calc(x,k,);
for(int i=head[x];i;i=e[i].next)if(!vis[e[i].to]){
calc(e[i].to,k-e[i].v*,-);
sum=sz[e[i].to];rt=;
getroot(e[i].to,);
work(rt);
}
}
int main(){
// freopen("test.in","r",stdin);
scanf("%d",&n);
for(int i=;i<n;i++){
int x,y,z;scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
}
scanf("%d",&k);
sum=mx[]=n;rt=;ans=;
getroot(,);
work(rt);
printf("%d\n",ans);
}

1468: Tree

Time Limit: 10 Sec  Memory Limit: 64 MB
Submit: 1099  Solved: 581
[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

Sample Output

5