RT,调了好长时间了
#include<bits/stdc++.h>
#define eps 1e-7
#define re register
#define N 1001001
#define MAX 2001
#define PI 3.1415927
using namespace std;
typedef long long ll;
typedef double db;
inline void read(re ll &ret)
{
ret=0;re ll pd=0;re char c=getchar();
while(!isdigit(c)){pd|=c=='-';c=getchar();}
while(isdigit(c)){ret=(ret<<1)+(ret<<3)+(c^48);c=getchar();}
ret=pd?-ret:ret;
return;
}
struct node
{
ll son[2],fa,siz,_siz;
bool tag;
}spy[N];
#define ls(x) spy[x].son[0]
#define rs(x) spy[x].son[1]
#define fa(x) spy[x].fa
#define siz(x) spy[x].siz
#define reverse(x) spy[x].tag^=1,swap(ls(x),rs(x))
#define ntroot(x) ls(fa(x))==x||rs(fa(x))==x
#define update(x) spy[x].siz=spy[ls(x)].siz+spy[rs(x)].siz+1+spy[x]._siz
inline void connect(re ll x,re ll y,re bool son)
{
fa(x)=y;
spy[y].son[son]=x;
return;
}
inline void pushdown(re ll x)
{
if(spy[x].tag)
{
if(ls(x))
reverse(ls(x));
if(rs(x))
reverse(rs(x));
spy[x].tag^=1;
}
return;
}
inline bool getson(re ll x)
{
return rs(fa(x))==x;
}
inline void rotate(re ll x)
{
re ll fat=fa(x);
re ll f=fa(fat);
re bool whfa=getson(x),whf=getson(fat);
if(ntroot(fat))
{
connect(x,f,whf);
connect(spy[x].son[!whfa],fat,whfa);
connect(fat,x,!whfa);
}
else
{
fa(x)=f;
connect(spy[x].son[!whfa],fat,whfa);
connect(fat,x,!whfa);
}
update(fat);
update(x);
return;
}
inline void pushall(re ll x)
{
if(ntroot(x))
pushall(fa(x));
pushdown(x);
return;
}
inline void splay(re ll x)
{
pushall(x);
re ll y;
while(ntroot(x))
{
y=fa(x);
if(ntroot(y))
{
if(getson(x)==getson(y))
rotate(y);
else
rotate(x);
}
rotate(x);
}
return;
}
inline void access(re ll x)
{
re ll y=0;
while(x)
{
splay(x);
spy[x]._siz+=spy[rs(x)].siz-spy[y].siz;
rs(x)=y;
update(x);
x=fa(y=x);
}
return;
}
inline void makeroot(re ll x)
{
access(x);
splay(x);
reverse(x);
update(x);
return;
}
inline void link(re ll x,re ll y)
{
makeroot(x);
makeroot(y);
fa(x)=y;
spy[y]._siz+=siz(x);
update(x);
update(y);
return;
}
inline void cut(re ll x,re ll y)
{
makeroot(x);
access(y);
rs(x)=fa(y)=0;
update(x);
update(y);
return;
}
inline void split(re ll x,re ll y)
{
makeroot(x);
access(y);
splay(y);
return;
}
ll n,q,x,y;
char s[N];
int main()
{
read(n);
read(q);
while(q--)
{
scanf("%s",s+1);
read(x);
read(y);
if(s[1]=='A')
{
link(x,y);
update(x);
update(y);
}
else if(s[1]=='Q')
{
cut(x,y);
makeroot(x);
makeroot(y);
printf("%lld\n",siz(x)*siz(y));
link(x,y);
}
}
exit(0);
}