hdu 4010 Query on The Trees
天呢, ,,,,,我记得做这个题的时候都开始叫骂了。。
还是普通的lct(本蒟蒻能会这个感觉就很强了。。。)
1 #include<bits/stdc++.h> 2 #define N 300005 3 #define LL long long 4 #define inf 0x3f3f3f3f 5 #define ls c[x][0] 6 #define rs c[x][1] 7 using namespace std; 8 inline int ra() 9 { 10 int x=0,f=1; char ch=getchar(); 11 while (ch<'0' || ch>'9') {if (ch=='-') f=-1; ch=getchar();} 12 while (ch>='0' && ch<='9') {x=x*10+ch-'0'; ch=getchar();} 13 return x*f; 14 } 15 int n,q[N],fa[N],mx[N],val[N],c[N][2],tag[N]; 16 bool rev[N]; int top,cnt; 17 void update(int x) 18 { 19 mx[x]=max(val[x],max(mx[ls],mx[rs])); 20 } 21 void pushdown(int x) 22 { 23 if (rev[x]) 24 { 25 rev[x]=0; rev[ls]^=1; rev[rs]^=1; swap(ls,rs); 26 } 27 if (tag[x]) 28 { 29 if (ls) tag[ls]+=tag[x],val[ls]+=tag[x],mx[ls]+=tag[x]; 30 if (rs) val[rs]+=tag[x],tag[rs]+=tag[x],mx[rs]+=tag[x]; 31 tag[x]=0; 32 } 33 } 34 bool which(int x){return c[fa[x]][1]==x;} 35 bool isroot(int x){return c[fa[x]][0]!=x && c[fa[x]][1]!=x;} 36 void rotate(int &x) 37 { 38 int y=fa[x],z=fa[y]; bool nx=which(x),ny=which(y); 39 if (!isroot(y)) c[z][ny]=x; fa[x]=z; 40 c[y][nx]=c[x][!nx]; fa[c[x][!nx]]=y; 41 fa[y]=x; c[x][!nx]=y; update(y); update(x); 42 } 43 void splay(int &x) 44 { 45 top=0; q[++top]=x; 46 for (int i=x;!isroot(i);i=fa[i]) q[++top]=fa[i]; 47 while (top) pushdown(q[top--]); 48 while (!isroot(x)) 49 { 50 int y=fa[x],z=fa[y]; 51 if (!isroot(y)) 52 { 53 if (which(x)==which(y)) rotate(y); 54 else rotate(x); 55 } 56 rotate(x); 57 } 58 } 59 void access(int x) 60 { 61 for (int t=0; x; t=x,x=fa[x]) 62 splay(x),c[x][1]=t,update(x); 63 } 64 void makeroot(int x) 65 { 66 access(x); splay(x); rev[x]^=1; 67 } 68 bool find(int x, int y) 69 { 70 access(x); splay(x); while (c[x][0]) x=c[x][0]; 71 access(y); splay(y); while (c[y][0]) y=c[y][0]; 72 return x==y; 73 } 74 void link(int x, int y) 75 { 76 makeroot(x); fa[x]=y; 77 } 78 void cut(int x, int y) 79 { 80 access(y); splay(y); 81 fa[c[y][0]]=0; c[y][0]=0; update(y); //为什么换成fa[x]就会T..... ??????????????????fogfogfogfogfog.. 82 //是不是题上说的先把x作为根,然后把y和y的父节点断开是这个意思啊。。。 83 //这样也不对(会不会是数据的问题??fog) 84 } 85 void change(int x, int y, int w) 86 { 87 makeroot(x); access(y); splay(y); 88 val[y]+=w; mx[y]+=w; tag[y]+=w; 89 } 90 int ask(int x, int y) 91 { 92 makeroot(x); access(y); splay(y); 93 return mx[y]; 94 } 95 int main() 96 { 97 while (scanf("%d",&n)!=EOF) 98 { 99 for (int i=0; i<=n; i++) rev[i]=c[i][0]=c[i][1]=tag[i]=fa[i]=0; 100 for (int i=1; i<n; i++) {int x=ra(),y=ra();link(x,y);} 101 for (int i=1; i<=n; i++) mx[i]=val[i]=ra(); 102 int Q=ra(); 103 for (int i=1; i<=Q; i++) 104 { 105 int opt=ra(),x=ra(),y=ra(),w; 106 if (opt==1) {if (!find(x,y)) link(x,y); else puts("-1");} 107 if (opt==2) { if (x==y || !find(x,y)) puts("-1"); else makeroot(x),cut(fa[y],y);} 108 if (opt==3) {w=ra();if (find(y,w)) change(y,w,x); else puts("-1");} 109 if (opt==4) {if (find(x,y)) printf("%d\n",ask(x,y)); else puts("-1");} 110 } 111 cout<<endl; 112 } 113 return 0; 114 }