【点分治】Tree

传送门:BZOJ1468


思路:点分一下就好了。


代码如下:

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
#include<bits/stdc++.h>
using namespace std;
#define N 60000
int n,m,x,y,z,rt,xb,tot,ans,sz[N],mx[N],d[N],head[N];
bool vis[N];
struct edge{int v,nxt,l;}e[N*2];
void add(int x,int y,int z){e[++tot].v=y; e[tot].nxt=head[x]; e[tot].l=z; head[x]=tot;}
void getroot(int u,int fa,int sum){
sz[u]=1; mx[u]=0;
for (int i=head[u],v;i;i=e[i].nxt){
if ((v=e[i].v)==fa || vis[v]) continue;
getroot(v,u,sum);
sz[u]+=sz[v];
mx[u]=max(mx[u],sz[v]);
}
mx[u]=max(mx[u],sum-sz[u]);
if (mx[u]<mx[rt]) rt=u;
}
void getdist(int u,int fa,int dist){
d[++xb]=dist;
for (int i=head[u],v;i;i=e[i].nxt)
if ((v=e[i].v)!=fa && !vis[v]) getdist(v,u,dist+e[i].l);
}
int calc(int u,int dist){
int ret=0; xb=0;
getdist(u,0,dist); sort(d+1,d+xb+1);
int i=1,j=xb;
while (i<j){
while (d[i]+d[j]>m && i<j) j--;
ret+=j-i; i++;
}
return ret;
}
void solve(int u){
vis[u]=1; ans+=calc(u,0);
for (int i=head[u],v;i;i=e[i].nxt){
if (vis[v=e[i].v]) continue;
ans-=calc(v,e[i].l);
rt=0; getroot(v,0,sz[v]);
solve(rt);
}
}
int main(){
scanf("%d",&n);
for (int i=1;i<n;i++){
scanf("%d%d%d",&x,&y,&z);
add(x,y,z); add(y,x,z);
}
scanf("%d",&m);
mx[0]=0x3f3f3f3f; rt=0; getroot(1,0,n); solve(rt);
printf("%d\n",ans);
return 0;
}