spoj qtree动态树
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define maxn 21000
int nn,n;
int e[maxn],v[maxn],ne[maxn],w[maxn],fa[maxn];
void add(int x,int y,int z){
ne[++nn]=e[x],e[x]=nn,v[nn]=y,w[nn]=z;
}
struct node{
node *ch[2],*pre;
int maxx,val,rt;
}tree[maxn];
node *null;
void init(){
memset(e,0,sizeof(e));
nn=0;
null=&tree[0];
null->maxx=-0x3fffffff;
null->val=-0x3fffffff;
for(int i=1;i<=n;i++){
tree[i].pre=tree[i].ch[0]=tree[i].ch[1]=null;
tree[i].rt=1;
tree[i].maxx=0;
}
}
void up(node *x){
x->maxx=max(x->ch[0]->maxx,max(x->ch[1]->maxx,x->val));
}
void dfs(int x,int fa,int ww){
tree[x].pre=(&tree[fa]);
tree[x].val=tree[x].maxx=ww;
for(int i=e[x];i;i=ne[i])if(v[i]!=fa)dfs(v[i],x,w[i]);
}
void rotate(node *x){
node *y=x->pre,*z=y->pre;
int k=x==y->ch[0];
y->ch[!k]=x->ch[k];
x->ch[k]->pre=y;
x->ch[k]=y;
y->pre=x;
x->pre=z;
if(!y->rt)z->ch[z->ch[1]==y]=x;
else{
y->rt=0;
x->rt=1;
}
up(y);
}
void splay(node *x){
for(up(x);!x->rt;){
node *y=x->pre,*z=y->pre;
if(y->rt)rotate(x);
else if((z->ch[1]==y)==(y->ch[1]==x))rotate(y),rotate(x);
else rotate(x),rotate(x);
}
up(x);
}
node* acess(node *x){
node *y=null;
for(;x!=null;y=x,x=x->pre){
splay(x);
x->ch[1]->rt=1;
x->ch[1]=y;
y->rt=0;
up(x);
}
return y;
}
int ask(int a,int b){
acess(&tree[a]);
node *y=acess(&tree[b]);
splay(y);
if(y==(&tree[a]))return y->ch[1]->maxx;
int ma=y->ch[1]->maxx;
splay(&tree[a]);
return max(ma,tree[a].maxx);
}
void change(int a,int b){
splay(&tree[a]);
tree[a].val=b;
up(&tree[a]);
}
int cas;
char aa[10];
int main(){
cin>>cas;
while(cas--){
memset(fa,-1,sizeof(fa));
scanf("%d",&n);
init();
for(int i=1;i<n;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
queue<int> jj;
jj.push(1);
tree[1].val=0;
tree[1].pre=null;
while(!jj.empty()){
int x=jj.front();
jj.pop();
for(int i=e[x];i;i=ne[i]){
if(&tree[v[i]]==tree[x].pre)continue;
tree[v[i]].pre=&tree[x];
tree[v[i]].val=tree[v[i]].maxx=w[i];
fa[v[i]]=x;
jj.push(v[i]);
}
}
while(1){
scanf("%s",aa);
if(aa[1]=='O')break;
if(aa[1]=='U'){
int a,b;
scanf("%d%d",&a,&b);
if(a==b){
printf("0\n");continue;}
printf("%d\n",ask(a,b));
}else{
int a,b;
scanf("%d%d",&a,&b);
if(fa[v[a<<1]]==v[(a<<1)-1]){
change(v[a<<1],b);
}else{
change(v[(a<<1)-1],b);
}
}
}
}
}