hdu3966 树链剖分入门题

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
const int N=50010;
const int INF=1e9+10;
int n,m,Q;
int num[N];
int head[N];
int tot;
struct Edge{
	int to,nxt;
}edge[N*2];
void addEdge(int u,int v){
	edge[tot].to=v;
	edge[tot].nxt=head[u];
	head[u]=tot++;
}
int tim;
int siz[N],top[N],son[N];
int fa[N];
int rank[N];
int dep[N];
int tid[N];
void init(){
	tot=0;
	tim=0;
	memset(head,-1,sizeof head);
	memset(son,-1,sizeof son);
}
void dfs1(int u,int father,int d){
	dep[u]=d;
	fa[u]=father;
	siz[u]=1;
	for(int k=head[u];~k;k=edge[k].nxt){
		int v=edge[k].to;
		if(v!=father){
			dfs1(v,u,d+1);
			siz[u]+=siz[v];
			if(son[u]==-1 || siz[v]>siz[son[u]])
				son[u]=v;
		}
	}
}
void dfs2(int u,int tp){
	top[u]=tp;
	tid[u]=++tim;
	rank[tim]=u;
	if(son[u]==-1) return;
	dfs2(son[u],tp);
	for(int k=head[u];~k;k=edge[k].nxt){
		int v=edge[k].to;
		if(v!=son[u] && v!=fa[u]) dfs2(v,v);
	}
}
void swap(int &a,int &b){
	int tmp=a;a=b;b=tmp;
}

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int col[N<<2];
void PushUp(int rt){
}

void Build(int l,int r,int rt){
	col[rt]=0;
	if(l==r){
		col[rt]=num[rank[l]];
		return ;
	}
	int m=l+r>>1;
	Build(lson);
	Build(rson);
}
void PushDown(int rt){
	if(col[rt]){
		col[rt<<1]+=col[rt];
		col[rt<<1|1]+=col[rt];
		col[rt]=0;
	}
}

void Update(int L,int R,int v,int l,int r,int rt){
	if(L<=l && R>=r){
		col[rt]+=v;
		return ;
	}
	PushDown(rt);
	int m=l+r>>1;
	if(L<=m) Update(L,R,v,lson);
	if(R>m) Update(L,R,v,rson);
}
int Query(int l,int r,int rt,int val){
	if(l==r) return col[rt];
	PushDown(rt);
	int m=l+r>>1;
	if(val<=m) return Query(lson,val);
	else return Query(rson,val);
}
void Change(int x,int y,int val){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]]) swap(x,y);
		Update(tid[top[x]],tid[x],val,1,n,1);
		x=fa[top[x]];
	}
	if(dep[x]>dep[y]) swap(x,y);
	Update(tid[x],tid[y],val,1,n,1);
}
int main()
{
    //freopen("in","r",stdin);
    //freopen("out.txt","w",stdout);
	char op[6];
	while(scanf("%d%d%d",&n,&m,&Q)==3){
		init();
		for(int i=1;i<=n;i++) scanf("%d",num+i);
		for(int i=1;i<=m;i++){
			int u,v;
			scanf("%d%d",&u,&v);
			addEdge(u,v);
			addEdge(v,u);
		}
		dfs1(1,-1,0);
		dfs2(1,1);
		Build(1,n,1);

		while(Q--){
			scanf("%s",op);
			if(op[0]=='Q'){
				int a;
				scanf("%d",&a);
				printf("%d\n",Query(1,n,1,tid[a]));
			}else{
				int a,b,c;
				scanf("%d%d%d",&a,&b,&c);
				if(op[0]=='D') c=-c;
				Change(a,b,c);
			}
		}
	}
	
	
	return 0;
}

你可能感兴趣的:(hdu3966 树链剖分入门题)