一棵树上有 \(n\) 个节点,编号分别为 \(1\) 到 \(n\),每个节点都有一个权值 \(w\)。我们将以下面的形式来要求你对这棵树完成一些操作: I. CHANGE u t
: 把结点 \(u\) 的权值改为 \(t\) II. QMAX u v
: 询问从点 \(u\) 到点 \(v\) 的路径上的节点的最大权值 III. QSUM u v
: 询问从点 \(u\) 到点 \(v\) 的路径上的节点的权值和。
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);
}
}
}
原文:https://www.cnblogs.com/mollnn/p/13644503.html