20分钟码完,手速++;
不过这道题正解是LCT吗,感觉很奇怪啊。
#include<iostream>
#include<cstdio>
#define maxn 30005
using namespace std;
int fa[maxn],ch[maxn][2],rev[maxn];
int sum[maxn],v[maxn];
bool dir(int x)
{return x==ch[fa[x]][1];}
bool isroot(int x)
{return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;}
void up(int x)
{sum[x]=sum[ch[x][0]]+sum[ch[x][1]]+v[x];}
void down(int x)
{
if(rev[x])
{
rev[ch[x][0]]^=1;
rev[ch[x][1]]^=1;
swap(ch[x][0],ch[x][1]);
rev[x]=0;
}
}
void rotate(int x)
{
int y=fa[x],z=fa[y];
bool b=dir(x);int a=ch[x][!b];
if(!isroot(y))
ch[z][dir(y)]=x;
fa[y]=x;ch[x][!b]=y;
fa[x]=z;ch[y][b]=a;
if(a) fa[a]=y;
up(y);up(x);
}
int S[maxn],tot;
void splay(int x)
{
S[++tot]=x;
for(int i=x;!isroot(i);i=fa[i])
S[++tot]=fa[i];
while(tot) down(S[tot--]);
while(!isroot(x))
{
int y=fa[x],z=fa[y];
if(isroot(y))rotate(x);
else
{
bool b=dir(x),c=dir(y);
if(b^c) {rotate(y);rotate(x);}
else {rotate(x);rotate(x);}
}
}
}
void access(int x)
{
for(int t=0;x;t=x,x=fa[x])
splay(x),ch[x][1]=t,up(x);
}
void make_root(int x)
{access(x);splay(x);rev[x]^=1;}
void link(int x,int y)
{make_root(x);fa[x]=y;}
int f[maxn];
int find(int x)
{return f[x]==x?x:f[x]=find(f[x]);}
void read(int &a)
{
a=0;char c=getchar();
while(c<'0'||c>'9')
c=getchar();
while(c>='0'&&c<='9')
{
a*=10;a+=c-'0';
c=getchar();
}
}
char c[15];
int main()
{
int n;read(n);
for(int i=1;i<=n;i++)
{read(v[i]);f[i]=i;}
int q;read(q);
int x,y;
for(int i=1;i<=q;i++)
{
scanf("%s",c);
read(x);read(y);
if(c[0]=='b')
{
if(find(x)==find(y))
puts("no");
else
{
f[find(x)]=find(y);
puts("yes");
link(x,y);
}
}
if(c[0]=='p')
{
make_root(x);
v[x]=y;up(x);
}
if(c[0]=='e')
{
if(find(x)!=find(y))
puts("impossible");
else
{
make_root(x);access(y);splay(y);
printf("%d\n",sum[y]);
}
}
}
return 0;
}