洛谷3128 最大流(树链剖分)
传送门
【题目分析】
蒟蒻并不会树上差分。。。。。所以只能用树链剖分套线段树维护。。。。。
对于每条路径,都相当于将所有经过的点+1,最后查询最大值即可。
【代码~】
#include<bits/stdc++.h>
using namespace std;
const int MAXN=5e4+10;
const int MAXM=1e5+10;
int n,q,cnt;
int head[MAXN],depth[MAXN],siz[MAXN],fa[MAXN],son[MAXN],top[MAXN];
int nxt[MAXM],to[MAXM];
int dfn[MAXN],ys[MAXN],tot;
struct Tree{
int l,r;
int maxx,add;
}tr[MAXN<<2];
int Read(){
int i=0,f=1;
char c;
for(c=getchar();(c>'9'||c<'0')&&c!='-';c=getchar());
if(c=='-')
f=-1,c=getchar();
for(;c>='0'&&c<='9';c=getchar())
i=(i<<3)+(i<<1)+c-'0';
return i*f;
}
void add(int x,int y){
nxt[cnt]=head[x];
head[x]=cnt;
to[cnt]=y;
cnt++;
}
void dfs1(int u,int f){
siz[u]=1;
for(int i=head[u];i!=-1;i=nxt[i]){
int v=to[i];
if(v==f)
continue;
depth[v]=depth[u]+1,fa[v]=u;
dfs1(v,u);
siz[u]+=siz[v];
if(siz[v]>siz[son[u]])
son[u]=v;
}
}
void dfs2(int u,int tp){
top[u]=tp;
dfn[u]=++tot;
if(!son[u])
return ;
dfs2(son[u],tp);
for(int i=head[u];i!=-1;i=nxt[i]){
int v=to[i];
if(v==fa[u]||v==son[u])
continue;
dfs2(v,v);
}
}
void push_up(int root){
tr[root].maxx=max(tr[root<<1].maxx,tr[root<<1|1].maxx);
}
void push_now(int root,int v){
tr[root].maxx+=v;
tr[root].add+=v;
}
void push_down(int root){
if(tr[root].add){
push_now(root<<1,tr[root].add);
push_now(root<<1|1,tr[root].add);
tr[root].add=0;
}
}
void build(int root,int l,int r){
tr[root].l=l,tr[root].r=r;
if(l==r)
return ;
int mid=l+r>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
}
void update(int root,int l,int r,int L,int R,int key){
if(l>R||r<L)
return ;
if(L<=l&&r<=R){
push_now(root,key);
return ;
}
push_down(root);
int mid=l+r>>1;
if(R<=mid)
update(root<<1,l,mid,L,R,key);
else{
if(L>mid)
update(root<<1|1,mid+1,r,L,R,key);
else
update(root<<1,l,mid,L,mid,key),update(root<<1|1,mid+1,r,mid+1,R,key);
}
push_up(root);
}
void updatepath(int x,int y){
while(top[x]!=top[y]){
if(depth[top[x]]<depth[top[y]])
swap(x,y);
update(1,1,n,dfn[top[x]],dfn[x],1);
x=fa[top[x]];
}
if(depth[x]<depth[y])
swap(x,y);
update(1,1,n,dfn[y],dfn[x],1);
}
int main(){
memset(head,-1,sizeof(head));
n=Read(),q=Read();
for(int i=1;i<n;++i){
int x=Read(),y=Read();
add(x,y),add(y,x);
}
dfs1(1,-1);
dfs2(1,1);
build(1,1,n);
while(q--){
int x=Read(),y=Read();
updatepath(x,y);
}
cout<<tr[1].maxx;
return 0;
}