bzoj3531 旅行 树链剖分

       树剖后直接对每一个宗教建立一颗线段树维护就好了。

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define N 100005
#define M 10000005
using namespace std;

int n,m,trtot,tot,dfsclk,a[N],b[N],d[N],fa[N],fst[N],pnt[N<<1],nxt[N<<1],pos[N],anc[N],sz[N],son[N];
struct node{ int x,y; }val[M]; int rt[N],ls[M],rs[M];
int read(){
	int x=0; char ch=getchar();
	while (ch<'0' || ch>'9') ch=getchar();
	while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
	return x;
}
void add(int x,int y){
	pnt[++tot]=y; nxt[tot]=fst[x]; fst[x]=tot;
}
void dfs(int x){
	int p; sz[x]=1;
	for (p=fst[x]; p; p=nxt[p]){
		int y=pnt[p];
		if (y!=fa[x]){
			fa[y]=x; d[y]=d[x]+1;
			dfs(y); sz[x]+=sz[y];
			if (sz[y]>sz[son[x]]) son[x]=y;
		}
	}
}
void divide(int x,int tp){
	anc[x]=tp; pos[x]=++dfsclk; int p;
	if (son[x]) divide(son[x],tp);
	for (p=fst[x]; p; p=nxt[p]){
		int y=pnt[p];
		if (y!=fa[x] && y!=son[x]) divide(y,y);
	}
}
void mdy(int &k,int l,int r,int x,int y){
	if (!k) k=++trtot;
	if (l==r){ val[k].x=val[k].y=y; return; }
	int mid=(l+r)>>1;
	if (x<=mid) mdy(ls[k],l,mid,x,y); else mdy(rs[k],mid+1,r,x,y);
	val[k].x=val[ls[k]].x+val[rs[k]].x; val[k].y=max(val[ls[k]].y,val[rs[k]].y);
}
node qry(int k,int l,int r,int x,int y){
	if (l==x && r==y || !k) return val[k]; int mid=(l+r)>>1;
	if (y<=mid) return qry(ls[k],l,mid,x,y); else
	if (x>mid) return qry(rs[k],mid+1,r,x,y); else{
		node t1=qry(ls[k],l,mid,x,mid),t2=qry(rs[k],mid+1,r,mid+1,y);
		t1.x+=t2.x; t1.y=max(t1.y,t2.y); return t1;
	}
}
int main(){
	n=read(); m=read(); int i,x,y;
	for (i=1; i<=n; i++){
		a[i]=read(); b[i]=read();
	}
	for (i=1; i<n; i++){
		x=read(); y=read();
		add(x,y); add(y,x);
	}
	dfs(1); divide(1,1);
	for (i=1; i<=n; i++) mdy(rt[b[i]],1,n,pos[i],a[i]);
	char ch; int ans,k;
	while (m--){
		ch=getchar(); while (ch<'A' || ch>'Z') ch=getchar(); ch=getchar();
		x=read(); y=read();
		if (ch=='C'){
			mdy(rt[b[x]],1,n,pos[x],0); b[x]=y;
			mdy(rt[y],1,n,pos[x],a[x]);
		} else if (ch=='W'){
			a[x]=y; mdy(rt[b[x]],1,n,pos[x],y);
		} else if (ch=='S'){
			ans=0; k=b[x];
			for (; anc[x]!=anc[y]; x=fa[anc[x]]){
				if (d[anc[x]]<d[anc[y]]) swap(x,y);
				ans+=qry(rt[k],1,n,pos[anc[x]],pos[x]).x;
			}
			if (pos[x]>pos[y]) swap(x,y); ans+=qry(rt[k],1,n,pos[x],pos[y]).x;
			printf("%d\n",ans);
		} else if (ch=='M'){
			ans=0; k=b[x];
			for (; anc[x]!=anc[y]; x=fa[anc[x]]){
				if (d[anc[x]]<d[anc[y]]) swap(x,y);
				ans=max(ans,qry(rt[k],1,n,pos[anc[x]],pos[x]).y);
			}
			if (pos[x]>pos[y]) swap(x,y); ans=max(ans,qry(rt[k],1,n,pos[x],pos[y]).y);
			printf("%d\n",ans);
		}
	}
	return 0;
}


by lych

2016.4.4

你可能感兴趣的:(线段树,树链剖分)