[ZJOI2008] 樹的統計 - LCT
阿新 • • 發佈:2020-09-10
Description
一棵樹上有 \(n\) 個節點,編號分別為 \(1\) 到 \(n\),每個節點都有一個權值 \(w\)。我們將以下面的形式來要求你對這棵樹完成一些操作: I. CHANGE u t
: 把結點 \(u\) 的權值改為 \(t\) II. QMAX u v
: 詢問從點 \(u\) 到點 \(v\) 的路徑上的節點的最大權值 III. QSUM u v
: 詢問從點 \(u\) 到點 \(v\) 的路徑上的節點的權值和。
Solution
LCT 維護鏈上資訊即可
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 1000000; int n,m,val[N]; namespace lct { int top, q[N], ch[N][2], fa[N], rev[N]; int a[N], b[N], tag[N], siz[N]; inline void pushup(int x) { a[0] = b[0] = siz[0] = 0; b[0] = -1e9; a[x] = a[ch[x][0]] + a[ch[x][1]] + val[x]; b[x] = max(max(b[ch[x][0]],b[ch[x][1]]),val[x]); siz[x] = siz[ch[x][0]] + siz[ch[x][1]] + 1; } inline void pushdown(int x) { if(rev[x]) { rev[ch[x][0]]^=1; rev[ch[x][1]]^=1; rev[x]^=1; swap(ch[x][0],ch[x][1]); } } inline bool isroot(int x) { return ch[fa[x]][0]!=x && ch[fa[x]][1]!=x; } inline void rotate(int p) { int q=fa[p], y=fa[q], x=ch[fa[p]][1]==p; ch[q][x]=ch[p][x^1]; fa[ch[q][x]]=q; ch[p][x^1]=q; fa[q]=p; fa[p]=y; if(y) if(ch[y][0]==q) ch[y][0]=p; else if(ch[y][1]==q) ch[y][1]=p; pushup(q); pushup(p); } inline void splay(int x) { q[top=1]=x; for(int i=x; !isroot(i); i=fa[i]) q[++top]=fa[i]; for(int i=top; i; i--) pushdown(q[i]); for(; !isroot(x); rotate(x)) if(!isroot(fa[x])) rotate((ch[fa[x]][0]==x)==(ch[fa[fa[x]]][0]==fa[x])?fa[x]:x); } void access(int x) { for(int t=0; x; t=x,x=fa[x]) splay(x),ch[x][1]=t,pushup(x); } void makeroot(int x) { access(x); splay(x); rev[x]^=1; } int find(int x) { access(x); splay(x); while(ch[x][0]) x=ch[x][0]; return x; } void split(int x,int y) { makeroot(x); access(y); splay(y); } void cut(int x,int y) { split(x,y); if(ch[y][0]==x) ch[y][0]=0, fa[x]=0; } void link(int x,int y) { makeroot(x); fa[x]=y; pushup(y); } int query(int x,int y) { split(x,y); return a[y]; } int querym(int x,int y) { split(x,y); return b[y]; } void modify(int p,int v) { split(p,p); val[p]=v; pushup(p); } } signed main() { ios::sync_with_stdio(false); cin>>n; for(int i=1;i<=n;i++) { lct::siz[i]=1; } for(int i=1;i<n;i++) { int u,v; cin>>u>>v; lct::link(u,v); } for(int i=1;i<=n;i++) { int v; cin>>v; lct::modify(i,v); } cin>>m; for(int i=1;i<=m;i++) { string str; cin>>str; int t1,t2; cin>>t1>>t2; if(str=="QMAX") { cout<<lct::querym(t1,t2)<<endl; } if(str=="QSUM") { cout<<lct::query(t1,t2)<<endl; } if(str=="CHANGE") { lct::modify(t1,t2); } } }