题目描述:
给定一棵n个节点的树,有两个操作:
-
CHANGE i ti 把第i条边的边权变成ti
-
QUERY a b 输出从a到b的路径中最大的边权,当a=b的时候,输出0
解析:
树链剖分,将边权转移到点权上。
代码:
#include <bits/stdc++.h>
using namespace std;
const int Max=200010;
int n,m,s,tot;
int first[Max],size[Max],son[Max],top[Max],fa[Max],dep[Max];
int rev[Max],seg[Max],tree[Max<<2],num[Max],id[Max],u[Max],v[Max];
struct shu{int to,next,len;};
shu edge[Max<<1];
char ch[10];
inline int get_int()
{
int x=0,f=1;
char c;
for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
if(c=='-') f=-1,c=getchar();
for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
return x*f;
}
inline void print(int x)
{
if(x>9) print(x/10);
putchar('0'+x%10);
}
inline void build(int x,int y,int z)
{
edge[++s].next=first[x];
first[x]=s;
edge[s].to=y,edge[s].len=z;
}
inline void dfs1(int point)
{
size[point]=1;
for(int u=first[point];u;u=edge[u].next)
{
int to=edge[u].to;
if(to==fa[point]) continue;
num[to]=edge[u].len,fa[to]=point,dep[to]=dep[point]+1;
dfs1(to),size[point]+=size[to];
if(size[to]>size[son[point]]) son[point]=to;
}
}
inline void dfs2(int point,int tp)
{
top[point]=tp,seg[rev[point]=++tot]=point;
if(!son[point]) return;
dfs2(son[point],tp);
for(int u=first[point];u;u=edge[u].next)
{
int to=edge[u].to;
if(to==fa[point]||to==son[point]) continue;
top[to]=to,seg[rev[to]=++tot]=to,dfs2(to,to);
}
}
inline void update(int root){tree[root]=max(tree[root<<1],tree[root<<1|1]);}
inline void buildtree(int root,int l,int r)
{
if(l==r){tree[root]=num[seg[l]];return;}
int mid=(l+r)>>1;
buildtree(root<<1,l,mid),buildtree(root<<1|1,mid+1,r);
update(root);
}
inline void change(int root,int l,int r,int pos,int num)
{
if(l==r&&l==pos){tree[root]=num;return;}
int mid=(l+r)>>1;
if(pos<=mid) change(root<<1,l,mid,pos,num);
else change(root<<1|1,mid+1,r,pos,num);
update(root);
}
inline int Q(int root,int l,int r,int L,int R)
{
if(L<=l&&R>=r) return tree[root];
int mid=(l+r)>>1,ans=-1e9;
if(L<=mid) ans=max(Q(root<<1,l,mid,L,R),ans);
if(R>mid) ans=max(Q(root<<1|1,mid+1,r,L,R),ans);
return ans;
}
inline int ask(int x,int y)
{
int ans=-1e9;
while(top[x]!=top[y])
{
if(dep[top[x]]<dep[top[y]]) swap(x,y);
ans=max(ans,Q(1,1,tot,rev[top[x]],rev[x]));
x=fa[top[x]];
}
if(dep[x]>dep[y]) swap(x,y);
ans=max(ans,Q(1,1,tot,rev[x]+1,rev[y]));
return ans;
}
int main()
{
n=get_int();
for(int i=1;i<n;i++)
{
int x=get_int(),y=get_int(),z=get_int();
build(x,y,z),build(y,x,z),u[i]=x,v[i]=y;
}
dfs1(1),dfs2(1,1),buildtree(1,1,tot);
for(int i=1;i<n;i++) id[i]=dep[u[i]]>dep[v[i]]?u[i]:v[i];
while(1)
{
scanf("%s",ch);
if(ch[0]=='D') break;
int x=get_int(),y=get_int();
if(ch[0]=='C') change(1,1,tot,rev[id[x]],y);
else
{
if(u!=v) print(ask(x,y)),putchar('\n');
else printf("0\n");
}
}
return 0;
}