【BZOJ】【P3052】【wc2013】【糖果公园】【题解】【树上莫队】

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3052

学长好强啊!!感觉学长的代码比vfk的代码可读性好多了 http://hzwer.com/5250.html

Code:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
typedef long long LL;
int n,m,q,col[maxn],Qsize,Csize,B,dfn[maxn],pre[maxn],vis[maxn],cnt[maxn],now;
LL V[maxn],W[maxn],anss[maxn],ans;
struct qes{int x,y,id,tm;}Q[maxn];
struct oper{int x,y,pre,tm;}C[maxn];
bool operator<(qes a,qes b){
	if(dfn[a.x]/B!=dfn[b.x]/B)return dfn[a.x]/B<dfn[b.x]/B; 
	if(dfn[a.y]/B!=dfn[b.y]/B)return dfn[a.y]/B<dfn[b.y]/B;
	if(a.tm/B!=b.tm/B)return a.tm/B<b.tm/B;
	return a.tm<b.tm;
}
vector<int>G[maxn];
int tot=0;
int siz[maxn],son[maxn],top[maxn],z,mp[maxn],fa[maxn],dep[maxn];
void dfs(int u){
	dfn[u]=++tot;siz[u]=1;
	for(int i=0,v;i<G[u].size();i++){
		if((v=G[u][i])!=fa[u]){
			fa[v]=u;dep[v]=dep[u]+1;
			dfs(v);siz[u]+=siz[v];
			if(siz[v]>siz[son[u]])son[u]=v;
		}
	}
}
void build(int u,int tp){
	mp[u]=++z;top[u]=tp;
	if(son[u])build(son[u],tp);
	for(int i=0,v;i<G[u].size();i++)if((v=G[u][i])!=fa[u]&&v!=son[u])
	build(v,v);
}
int lca(int u,int v){
	while(top[u]!=top[v]){
		if(dep[top[u]]<dep[top[v]])swap(u,v);
		u=fa[top[u]];
	}return dep[u]<dep[v]?u:v;
}
void vxor(int x){
	if(vis[x])ans-=(LL)W[cnt[col[x]]]*V[col[x]],cnt[col[x]]--;
	else cnt[col[x]]++,ans+=(LL)W[cnt[col[x]]]*V[col[x]];	
	vis[x]^=1;
}
void change(int x,int y){
	if(vis[x]){
		vxor(x);col[x]=y;vxor(x);
	}else col[x]=y;
}
void TimeMachine(int tar){//XD
	for(int i=now+1;i<=tar;i++)change(C[i].x,C[i].y);
	for(int i=now;i>tar;i--)change(C[i].x,C[i].pre);
	now=tar;
}
void vxor(int x,int y){
	while(x!=y)if(dep[x]>dep[y])vxor(x),x=fa[x];
	else vxor(y),y=fa[y];
}
int getint(){
	int res=0;char c=getchar();
	while(!isdigit(c))c=getchar();
	while(isdigit(c))res=res*10+c-'0',c=getchar();
	return res;
}
int main(){
	n=getint();m=getint();q=getint();B=pow(n,2.0/3.0);
	for(int i=1;i<=m;i++)V[i]=getint();
	for(int i=1;i<=n;i++)W[i]=getint();
	for(int i=1;i<n;i++){
		int u=getint(),v=getint();
		G[u].push_back(v);
		G[v].push_back(u);
	}
	dfs(1);
	build(1,1);
	for(int i=1;i<=n;i++)pre[i]=col[i]=getint();
	for(int i=1;i<=q;i++){
		int ty=getint(),x=getint(),y=getint();
		if(ty&&dfn[x]>dfn[y])swap(x,y);
		if(ty==0) C[++Csize]=(oper){x,y,pre[x],i},pre[x]=y;
		else Q[Qsize+1]=(qes){x,y,Qsize+1,Csize},Qsize++;		
	}sort(Q+1,Q+1+Qsize);
	int u=Q[1].x,v=Q[1].y;
	TimeMachine(Q[1].tm);
	vxor(Q[1].x,Q[1].y);
	int LCA=lca(Q[1].x,Q[1].y);
	vxor(LCA);anss[Q[1].id]=ans;vxor(LCA);	
	for(int i=2;i<=Qsize;i++){
		TimeMachine(Q[i].tm);
		vxor(Q[i-1].x,Q[i].x);
		vxor(Q[i-1].y,Q[i].y);
		int LCA=lca(Q[i].x,Q[i].y);
		vxor(LCA);
		anss[Q[i].id]=ans;
		vxor(LCA);
	}for(int i=1;i<=Qsize;i++)printf("%lld\n",anss[i]);
	return 0;
}


你可能感兴趣的:(bzoj)