1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
| #include <iostream>
#include <cstdio>
using namespace std;
const int INF = 1<<30;
const int maxn = 30233;
typedef long long LL;
int getint() {
int r = 0, k = 1; char c = getchar();
for (; '0' > c || c > '9'; c = getchar()) if (c == '-') k = -1;
for (; '0' <= c && c <= '9'; c = getchar()) r = r * 10 - '0' + c;
return r * k;
}
char getop() {
char c;
for (c = getchar(); 'a' > c || c > 'z'; c = getchar());
return c;
}
int n,m;
int rev[maxn],sum[maxn],c[maxn][2],p[maxn],fa[maxn];
void pd(int x) {
if (rev[x]) {
rev[c[x][0]]^=1;rev[c[x][1]]^=1;rev[x]=0;
swap(c[x][0],c[x][1]);
}
}
void pu(int x) {
sum[x] = sum[c[x][0]]+sum[c[x][1]]+p[x];
}
bool isroot(int x){
return c[fa[x]][0]!=x&&c[fa[x]][1]!=x;
}
int ws(int x) {
return c[fa[x]][1]==x;
}
void rotate(int x) {
int y=fa[x],z=fa[y],a=ws(x),b=!a;
if(!isroot(y)){
if(y==c[z][0]) c[z][0]=x;
else c[z][1]=x;
}
fa[x]=z;fa[y]=x;fa[c[x][b]]=y;
c[y][a]=c[x][b];c[x][b]=y;
pu(y); pu(x);
}
int st[maxn];
void splay(int x) {
int tail = 1; st[1] = x;
for (int i=x;!isroot(i);i=fa[i]) st[++tail]=fa[i];
while(tail) pd(st[tail--]);
while (!isroot(x)) {
int y=fa[x],z=fa[y];
if(!isroot(y)){
if(c[y][0]==x^c[z][0]==y)rotate(x);
else rotate(y);
}
rotate(x);
}
}
void access(int x){
int y = 0;
while(x) {
splay(x);
c[x][1]=y;
pu(x); //Attention!
y=x;x=fa[x];
}
}
void mkrt(int x) {
access(x); splay(x); rev[x] ^= 1;
}
void link(int u,int v) {
mkrt(u);
fa[u]=v;
splay(u);
}
void cut(int u,int v) {
mkrt(u);
access(v);
splay(v);
fa[u]=0;
c[v][0]=0;
}
int ask(int x, int y) {
mkrt(x);
access(y);
splay(y);
return sum[y];//
}
void change(int pos, int x) {
mkrt(pos);
p[pos]=x;
pu(pos);
}
int findrt(int x) {
access(x); splay(x); //Forgot
while (c[x][0]) x = c[x][0];
splay(x);
return x;
}
int main() {
n = getint();int x;
for (int i = 1; i <= n; ++i) {
x=getint();
p[i]=sum[i]=x;
}
m=getint();
char op; int y;
while(m--) {
op = getop();
x = getint(); y = getint();
if (op == 'b') {
if (findrt(x)==findrt(y)) {
printf("no\n");
} else {
printf("yes\n");
link(x, y);
}
continue;
}
if (op == 'p'){
change(x,y);
continue;
}
if (findrt(x)!=findrt(y)) {
printf("impossible\n");
} else {
printf("%d\n", ask(x,y));
}
}
return 0;
}
|