动态树LCT

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cmath>
  4 #include<algorithm>
  5 using namespace std;
  6 const int maxn=100000+10,INF=-1u>>1;
  7 int v[maxn],maxv[maxn],minv[maxn],sumv[maxn],ch[maxn][2],pre[maxn],top[maxn],flip[maxn],n,Q;
  8 inline int read(){
  9     int x=0,sig=1;char ch=getchar();
 10     while(!isdigit(ch)){if(ch=='-') sig=-1;ch=getchar();}
 11     while(isdigit(ch)) x=10*x+ch-'0',ch=getchar();
 12     return x*=sig;
 13 }
 14 inline void write(int x){
 15     if(x==0){putchar('0');return;}if(x<0) putchar('-'),x=-x;
 16     int len=0,buf[15];while(x) buf[len++]=x%10,x/=10;
 17     for(int i=len-1;i>=0;i--) putchar(buf[i]+'0');return;
 18 }
 19 void maintain(int o){
 20     int lc=ch[o][0],rc=ch[o][1];
 21     maxv[o]=max(maxv[lc],maxv[rc]);
 22     minv[o]=min(minv[lc],minv[rc]);
 23     sumv[o]=sumv[lc]+sumv[rc];
 24     if(v[o]){
 25         sumv[o]+=v[o];
 26         maxv[o]=max(maxv[o],v[o]);
 27         minv[o]=min(minv[o],v[o]);
 28     } return;
 29 }
 30 void pushdown(int o){
 31     if(flip[o]){
 32         flip[ch[o][0]]^=1;
 33         flip[ch[o][1]]^=1;
 34         swap(ch[o][0],ch[o][1]);
 35         flip[o]=0;
 36     } return;
 37 }
 38 void rotate(int x,int d){
 39     pushdown(x);
 40     int y=pre[x],z=pre[y];
 41     ch[y][d^1]=ch[x][d];pre[ch[x][d]]=y;
 42     ch[z][ch[z][1]==y]=x;pre[x]=z;
 43     ch[x][d]=y;pre[y]=x;
 44     maintain(y);return;
 45 }
 46 void splay(int x){
 47     int rt=x;
 48     while(pre[rt]) rt=pre[rt];
 49     if(x!=rt){
 50         top[x]=top[rt];top[rt]=0;
 51         while(pre[x]){
 52             pushdown(pre[x]);
 53             rotate(x,ch[pre[x]][0]==x);
 54         } maintain(x);
 55     } else pushdown(x);
 56     return;
 57 }
 58 void access(int x){
 59     int y=0;
 60     while(x){
 61         splay(x);
 62         top[ch[x][1]]=x;pre[ch[x][1]]=0;
 63         ch[x][1]=y;
 64         top[y]=0;pre[y]=x;
 65         maintain(x);
 66         y=x;x=top[x];
 67     } return;
 68 }
 69 void makeroot(int x){
 70     access(x);splay(x);flip[x]^=1;return;
 71 }
 72 void link(int u,int v){
 73     makeroot(u);top[u]=v;return;
 74 }
 75 void query(int x,int y){
 76     if(x==y){
 77         puts("error");return;
 78     }
 79     makeroot(x);access(y);splay(y);
 80     write(maxv[y]);putchar(' ');write(minv[y]);putchar(' ');write(sumv[y]);putchar('
');
 81     return;
 82 }
 83 void update(int pos,int cv){
 84     splay(pos);v[pos]=cv;
 85     maintain(pos);return;
 86 }
 87 void init(){
 88     maxv[0]=-INF;minv[0]=INF;sumv[0]=0;
 89     n=read();
 90     for(int i=1;i<n;i++){
 91         int a=read(),b=read(),c=read();
 92         v[i+n]=c;
 93         link(a,i+n);link(i+n,b);
 94     }
 95     Q=read();
 96     while(Q--)
 97     {
 98         int tp=read(),a=read(),b=read();
 99         if(tp) query(a,b);
100         else update(a+n,b);
101     }
102     return ;
103 }
104 int main(){init();return 0;}
原文地址:https://www.cnblogs.com/chxer/p/4456363.html