题目大意:
给出一棵树,点上有点权
有两种询问,询问两点之间树链上的点权和,询问两点之间树链上最大点权
点数<=30000,询问树<=200000
最裸的动态树,操作少,维护的值简单
//Lib #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<ctime> #include<iostream> #include<algorithm> #include<vector> #include<string> #include<queue> using namespace std; //Macro #define rep(i,a,b) for(int i=a,tt=b;i<=tt;++i) #define rrep(i,a,b) for(int i=a,tt=b;i>=tt;--i) #define erep(i,e,x) for(int i=x;i;i=e[i].next) #define irep(i,x) for(__typedef(x.begin()) i=x.begin();i!=x.end();i++) #define read() (strtol(ipos,&ipos,10)) #define sqr(x) ((x)*(x)) #define pb push_back #define PS system("pause"); typedef long long ll; typedef pair<int,int> pii; const int oo=100000000; const double inf=1e20; const double eps=1e-6; string name="",in=".in",out=".out"; //Var struct E { int next,node; }e[60008]; struct T { int LC,RC,KEY,SUM,MAX,FA; #define lc(x) tree[x].LC #define rc(x) tree[x].RC #define key(x) tree[x].KEY #define sum(x) tree[x].SUM #define Max(x) tree[x].MAX #define fa(x) tree[x].FA }tree[30008]; int tot,n,Q,w[30008],h[30008]; bool vis[30008]; void add(int a,int b){e[++tot].next=h[a];e[tot].node=b;h[a]=tot;} bool isRoot(int x){return (lc(fa(x))!=x)&&(rc(fa(x))!=x);} void Update(int x) { sum(x)=sum(lc(x))+sum(rc(x))+key(x); Max(x)=max(max(Max(lc(x)),Max(rc(x))),key(x)); } void Zig(int x) { int y=fa(x),z=fa(y); if(lc(z)==y)lc(z)=x;else if(rc(z)==y)rc(z)=x; fa(x)=z;fa(rc(x))=y;lc(y)=rc(x);rc(x)=y;fa(y)=x; Update(y); } void Zag(int x) { int y=fa(x),z=fa(y); if(lc(z)==y)lc(z)=x;else if(rc(z)==y) rc(z)=x; fa(x)=z;fa(lc(x))=y;rc(y)=lc(x);lc(x)=y;fa(y)=x; Update(y); } void Splay(int x) { int y , z; while (!isRoot(x)) { y = fa(x); z = fa(y); if (isRoot(y)) if (x == lc(y)) Zig(x); else Zag(x); else if (y == lc(z)) if (x == lc(y)) Zig(y) , Zig(x); else Zag(x) , Zig(x); else if (x == lc(y)) Zig(x) , Zag(x); else Zag(y) , Zag(x); } Update(x); } void DFS(int u,int f) { key(u)=w[u]; erep(i,e,h[u])if(e[i].node!=f) DFS(e[i].node,u),fa(e[i].node)=u; } void Init() { int a,b; scanf("%d",&n); rep(i,1,n-1) { scanf("%d%d",&a,&b); add(a,b);add(b,a); } rep(i,1,n)scanf("%d",w+i); key(0)=Max(0)=-oo; DFS(1,0); } void Expose(int x) { int y; for(y=0;x;x=fa(x)){Splay(x);rc(x)=y;Update(x);y=x;} } void Change(int x,int y) { key(x)=y;Splay(x); } int Qmax(int x,int y) { Expose(y); for(y=0;x;x=fa(x)) { Splay(x); if(!fa(x))return max(key(x),max(Max(rc(x)),Max(y))); rc(x)=y;Update(x);y=x; } } int Qsum(int x,int y) { Expose(y); for(y=0;x;x=fa(x)) { Splay(x); if(!fa(x))return sum(rc(x))+key(x)+sum(y); rc(x)=y;Update(x);y=x; } } void Work() { char ch[10];int a,b; scanf("%d",&Q); rep(i,1,Q) { scanf("%s%d%d",ch,&a,&b); if(ch[0]=='C')Change(a,b); else { if(ch[1]=='M')printf("%d\n",Qmax(a,b)); else printf("%d\n",Qsum(a,b)); } } } int main() { //freopen((name+in).c_str(),"r",stdin); //freopen((name+out).c_str(),"w",stdout); Init(); Work(); return 0; }