不要脑子的题解
一共三步:
- 先把所有点的权值设为1,表示所有点都可以删。
- 对于每一个好点对,将两点间路径上的点的权值设为0。所有好点对处理完后记录下整棵树的权值和。
- 然后继续把坏点对路径上的点的权值设为0,记录整棵树的权值和,两次权值和的差即为答案。
用树剖+线段树维护即可。
#include<bits/stdc++.h>
#define lc (x<<1)
#define rc (x<<1|1)
#define mid ((l+r)>>1)
#define int long long
using namespace std;
const int N=1e6+15;
int n,m,fa[N],siz[N],dep[N],bs[N],top[N],c[N],d[N],id[N],dfn[N],dn,val[N<<2],tag[N<<2];
vector<int>lk[N];
void dfs(int u,int f){
fa[u]=f,dep[u]=dep[f]+1,siz[u]=1;
for(int v:lk[u]){
if(v==f)continue;
dfs(v,u);siz[u]+=siz[v];c[u]+=c[v],d[u]+=d[v];
if(!bs[u]||siz[v]>siz[bs[u]])bs[u]=v;
}
}
void hld(int u,int t){
top[u]=t,dfn[u]=++dn,id[dn]=u;
if(bs[u])hld(bs[u],t);
for(int v:lk[u]){
if(v==fa[u]||v==bs[u])continue;
hld(v,v);
}
}
int lca(int x,int y){
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]])swap(x,y);
x=fa[top[x]];
}
if(dep[x]<dep[y])swap(x,y);
return y;
}
void up(int x){
if(tag[x])val[x]=0;
else val[x]=val[lc]+val[rc];
}
void build(int x,int l,int r){
val[x]=tag[x]=0;
if(l==r)return val[x]=1,void();
build(lc,l,mid);build(rc,mid+1,r);
up(x);
}
void update(int x,int ul,int ur,int l,int r){
if(ul<=l&&ur>=r)return val[x]=0,tag[x]=1,void();
if(ul<=mid)update(lc,ul,ur,l,mid);
if(ur>mid)update(rc,ul,ur,mid+1,r);
up(x);
}
void update(int x,int y){
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]])swap(x,y);
update(1,dfn[top[x]],dfn[x],1,n);
x=fa[top[x]];
}
if(dep[x]<dep[y])swap(x,y);
update(1,dfn[y],dfn[x],1,n);
}
#undef int
int main(){
#define int long long
ios::sync_with_stdio(0);cin.tie(0);
int i,j,k,l,r,x,y,z;
cin>>n>>m;
build(1,1,n);
for(i=1;i<n;i++)cin>>x>>y,lk[x].push_back(y),lk[y].push_back(x);
dfs(1,0),hld(1,1);
for(i=1;i<=m;i++){
cin>>x>>y;
update(x,y);
}
cin>>x>>y;
l=val[1];update(x,y);
cout<<l-val[1];
return 0;
}再贴一份树上差分的代码:link