标签:过程 之间 char include push zoj 接下来 print 并且
题目描述
输入
输出
对于每个bridge命令与excursion命令,输出一行,为题目描述所示。
样例输入
5
4 2 4 5 6
10
excursion 1 1
excursion 1 2
bridge 1 2
excursion 1 2
bridge 3 4
bridge 3 5
excursion 4 5
bridge 1 3
excursion 2 4
excursion 2 5
样例输出
4
题解
明知道可以并查集+树剖却偏要使用LCT,为啥?因为好写啊~
在LCT的Splay Tree上维护一个sum,表示实子树的点权和。
然后模拟操作就行了,修改时直接Splay后修改就行。
#include <cstdio> #include <cstring> #include <algorithm> #define N 30010 using namespace std; int fa[N] , c[2][N] , w[N] , sum[N] , rev[N]; char str[15]; void pushup(int x) { sum[x] = sum[c[0][x]] + sum[c[1][x]] + w[x]; } void pushdown(int x) { if(rev[x]) { int l = c[0][x] , r = c[1][x]; swap(c[0][l] , c[1][l]) , swap(c[0][r] , c[1][r]); rev[l] ^= 1 , rev[r] ^= 1 , rev[x] = 0; } } bool isroot(int x) { return c[0][fa[x]] != x && c[1][fa[x]] != x; } void update(int x) { if(!isroot(x)) update(fa[x]); pushdown(x); } void rotate(int x) { int y = fa[x] , z = fa[y] , l = (c[1][y] == x) , r = l ^ 1; if(!isroot(y)) c[c[1][z] == y][z] = x; fa[x] = z , fa[y] = x , fa[c[r][x]] = y , c[l][y] = c[r][x] , c[r][x] = y; pushup(y) , pushup(x); } void splay(int x) { update(x); while(!isroot(x)) { int y = fa[x] , z = fa[y]; if(!isroot(y)) rotate((c[0][y] == x) ^ (c[0][z] == y) ? x : y); rotate(x); } } void access(int x) { int t = 0; while(x) splay(x) , c[1][x] = t , pushup(x) , t = x , x = fa[x]; } int find(int x) { access(x) , splay(x); while(c[0][x]) pushdown(x) , x = c[0][x]; return x; } void makeroot(int x) { access(x) , splay(x) , swap(c[0][x] , c[1][x]) , rev[x] ^= 1; } void link(int x , int y) { makeroot(x) , fa[x] = y; } int main() { int n , i , m , x , y; scanf("%d" , &n); for(i = 1 ; i <= n ; i ++ ) scanf("%d" , &w[i]) , sum[i] = w[i]; scanf("%d" , &m); while(m -- ) { scanf("%s%d%d" , str , &x , &y); if(str[0] == ‘b‘) { if(find(x) == find(y)) puts("no"); else puts("yes") , link(x , y); } else if(str[0] == ‘p‘) splay(x) , w[x] = y , pushup(x); else { if(find(x) != find(y)) puts("impossible"); else makeroot(x) , access(y) , splay(y) , printf("%d\n" , sum[y]); } } return 0; }
标签:过程 之间 char include push zoj 接下来 print 并且
原文地址:http://www.cnblogs.com/GXZlegend/p/7189990.html