WA 27 pts
查看原帖
WA 27 pts
602458
Rigel楼主2024/10/8 20:00

link

用的是树链剖分。

#include<bits/stdc++.h>
#define int long long
#define maxn 50010
using namespace std;
int n,m,tot,tim,rnk[maxn],t[maxn<<2],tag[maxn<<2],ans;
struct node{
	int lnk,dep,siz,fa,hson,top,dfn;
}a[maxn];
struct edge{
	int to,nxt;
}e[maxn<<1];
inline int read(){
	int ret=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9')ret=ret*10+(ch&15),ch=getchar();
	return ret*f;
}
void add_edge(int x,int y){
	e[++tot]=(edge){y,a[x].lnk};
	a[x].lnk=tot;
}
void dfs1(int u,int dep){
	a[u].dep=dep;
	a[u].siz=1;
	for(int i=a[u].lnk;i;i=e[i].nxt){
		int v=e[i].to;
		if(v==a[u].fa)continue;
		a[v].fa=u;
		dfs1(v,dep+1);
		a[u].siz+=a[v].siz;
		if(a[v].siz>a[a[u].hson].siz)a[u].hson=v;
	}
}
void dfs2(int u,int top){
	a[u].top=top;
	a[u].dfn=++tim;
	rnk[tim]=u;
	if(a[u].hson){
		dfs2(a[u].hson,top);
		for(int i=a[u].lnk;i;i=e[i].nxt){
			int v=e[i].to;
			if(v==a[u].fa||v==a[u].hson)continue;
			dfs2(v,v);
		}
	}
}
void push_up(int now){
	t[now]=t[now<<1]+t[(now<<1)|1];
}
void push_down(int now,int l,int r){
	if(l==r){
		tag[now]=0;
		return;
	}
	int lson=now<<1,rson=(now<<1)|1,mid=(l+r)>>1;
	tag[lson]+=tag[now],tag[rson]+=tag[now];
	t[lson]+=tag[now]*(mid-l+1),t[rson]+=tag[now]*(r-mid);
	tag[now]=0;
}
void Update(int x,int y,int now,int l,int r){
	if(x<=l&&r<=y){
		t[now]+=r-l+1;
		tag[now]++;
		return;
	}
	int lson=now<<1,rson=(now<<1)|1,mid=(l+r)>>1;
	push_down(now,l,r);
	if(x<=mid)Update(x,y,lson,l,mid);
	if(mid+1<=y)Update(x,y,rson,mid+1,r);
	push_up(now);
}
void path_update(int u,int v){
	while(a[u].top!=a[v].top){
		if(a[a[u].top].dep<a[a[v].top].dep)swap(u,v);
		Update(a[a[u].top].dfn,a[u].dfn,1,1,n);
		u=a[a[u].top].fa;
	}
	if(a[u].dep<a[v].dep)swap(u,v);
	Update(a[v].dfn,a[u].dfn,1,1,n);
}
void calc(int now,int l,int r){
	if(l==r){
		ans=max(ans,t[now]);
		return;
	}
	int lson=now<<1,rson=(now<<1)|1,mid=(l+r)>>1;
	calc(lson,l,mid),calc(rson,mid+1,r);
}
signed main(){
	n=read(),m=read();
	for(int i=1;i<n;i++){
		int u=read(),v=read();
		add_edge(u,v),add_edge(v,u);
	}
	dfs1(1,1),dfs2(1,1);
	while(m--){
		int u=read(),v=read();
		path_update(u,v);
	}
	calc(1,1,n);
	printf("%lld\n",ans);
	return 0;
}
2024/10/8 20:00
加载中...