bzoj2843 -- LCT

对于修改,将其splay到根再修改。

对于查询x,y路径上的权值和,先将x换到根,再access(y)、splay(y),sum[y]就是答案。

代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 inline char nc(){
 6     static char buf[100000],*p1=buf,*p2=buf;
 7     if(p1==p2){
 8         p2=(p1=buf)+fread(buf,1,100000,stdin);
 9         if(p1==p2)return EOF;
10     }
11     return *p1++;
12 }
13 inline void Read(int& x){
14     char c=nc();
15     for(;c<'0'||c>'9';c=nc());
16     for(x=0;c>='0'&&c<='9';x=(x<<3)+(x<<1)+c-48,c=nc());
17 }
18 inline void Read(char &C){
19     char c=nc();
20     while(c<'a'||c>'z')c=nc();
21     C=c;
22 }
23 char S[30];
24 int Len;
25 inline void Print(int x){
26     if(x==0)putchar(48);
27     for(Len=0;x;x/=10)S[++Len]=x%10;
28     for(;Len;)putchar(S[Len--]+48);putchar('\n');
29 }
30 #define N 30010
31 int i,j,k,n,x,y,m,f[N],ch[N][2],a[N],s[N];
32 bool b[N],r[N];
33 char c;
34 inline int Get(int x){return ch[f[x]][1]==x;}
35 inline void Update(int x){
36     if(x==0)return;
37     r[x]^=1;
38     swap(ch[x][0],ch[x][1]);
39 }
40 inline void Pushdown(int x){if(r[x])Update(ch[x][0]),Update(ch[x][1]),r[x]=0;}
41 inline void Pushup(int x){s[x]=s[ch[x][0]]+s[ch[x][1]]+a[x];}
42 inline void Rotate(int x){
43     bool d=Get(x);int y=f[x];
44     if(b[y])b[y]=0,b[x]=1;else ch[f[y]][Get(y)]=x;
45     ch[y][d]=ch[x][d^1];f[ch[y][d]]=y;
46     ch[x][d^1]=y;f[x]=f[y];f[y]=x;
47     Pushup(y);
48 }
49 inline void P(int x){
50     if(!b[x])P(f[x]);
51     Pushdown(x);
52 }
53 inline void Splay(int x){
54     P(x);
55     for(;!b[x];Rotate(x))
56     if(!b[f[x]])Rotate(Get(x)==Get(f[x])?f[x]:x);
57     Pushup(x);
58 }
59 inline int Access(int x){
60     int y=0;
61     while(x){
62         Splay(x);
63         b[ch[x][1]]=1;ch[x][1]=y;b[y]=0;
64         Pushup(x);y=x;x=f[x];
65     }
66     return y;
67 }
68 inline bool Judge(int x,int y){
69     while(f[x])x=f[x];
70     while(f[y])y=f[y];
71     return x==y;
72 }
73 inline void mr(int x){Access(x);Splay(x);Update(x);}
74 inline void Link(int x,int y){mr(x);f[x]=y;}
75 inline void Change(int x,int y){Splay(x);s[x]+=y-a[x];a[x]=y;}
76 inline int Query(int x,int y){
77     if(x==y)return a[x];
78     mr(x);Access(y);Splay(y);return s[y];
79 }
80 int main()
81 {
82     Read(n);
83     for(i=1;i<=n;i++)Read(a[i]),s[i]=a[i],b[i]=1;
84     Read(m);
85     while(m--){
86         Read(c);Read(x);Read(y);
87         if(c=='e')if(!Judge(x,y))puts("impossible");else Print(Query(x,y));else
88         if(c=='b')if(Judge(x,y))puts("no");else puts("yes"),Link(x,y);else Change(x,y);
89     }
90     return 0;
91 }
bzoj2843

 

posted @ 2017-03-11 11:11  gjghfd  阅读(232)  评论(0编辑  收藏  举报