暴力splay解决一切问题!!
如果不行,就再套一个!!
作为一个数据结构学傻了的菜鸡,这题当然是一眼splay啦
我们可以建30000棵splay,然后乱搞即可
query:标准splay区间操作,输出size即可
connect:搞到两点所在的splay的根节点,然后启发式合并即可
没啦,so easy!
代码:(可能有些丑,我从这里( https://www.luogu.org/contestnew/show/9354 ) 来的)
#include<bits/stdc++.h>
#define sz 101010
#define mod (int)(1e9+7)
using namespace std;
typedef long long ll;
struct FastIO
{
inline FastIO& operator>>(int& x)
{
x=0;char f=0,ch=getchar();
while(ch>'9'||ch<'0') f|=(ch=='-'),ch=getchar();
while(ch<='9'&&ch>='0') x=x*10+ch-48,ch=getchar();
return x=(f?-x:x),*this;
}
inline FastIO& operator>>(ll& x)
{
x=0;char f=0,ch=getchar();
while(ch>'9'||ch<'0') f|=(ch=='-'),ch=getchar();
while(ch<='9'&&ch>='0') x=x*10+ch-48,ch=getchar();
return x=(f?-x:x),*this;
}
inline FastIO& operator>>(double& x)
{
x=0;char f=0,ch=getchar();
double d=0.1;
while(ch>'9'||ch<'0') f|=(ch=='-'),ch=getchar();
while(ch<='9'&&ch>='0') x=x*10+ch-48,ch=getchar();
if(ch=='.')
{
ch=getchar();
while(ch<='9'&&ch>='0') x+=d*(ch^48),d*=0.1,ch=getchar();
}
return x=(f?-x:x),*this;
}
}read;
void file()
{
#ifndef ONLINE_JUDGE
freopen("a.txt","r",stdin);
#endif
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
ll a[sz];
struct hh{int fa,dep,ch[2];ll sum;}tr[sz<<1];
int getfa(int x){while (tr[x].fa) x=tr[x].fa;return x;}
void pushup(int x)
{
tr[x].sum=tr[tr[x].ch[0]].sum+tr[tr[x].ch[1]].sum+a[x];
tr[x].dep=max(tr[tr[x].ch[0]].dep,tr[tr[x].ch[1]].dep)+1;
}
bool get(int x){return tr[tr[x].fa].ch[1]==x;}
void rotate(int x)
{
int y=tr[x].fa,z=tr[y].fa;
int k=get(x),w=tr[x].ch[!k];
if (z) tr[z].ch[get(y)]=x;tr[x].ch[!k]=y;tr[y].ch[k]=w;
if (w) tr[w].fa=y;tr[x].fa=z;tr[y].fa=x;
pushup(y);pushup(x);
}
void splay(int x,int to)
{
while (tr[x].fa!=to)
{
int y=tr[x].fa;
if (tr[y].fa!=to) rotate(get(x)==get(y)?y:x);
rotate(x);
}
}
void connect(int x,int y) //head[x]->tail[y]
{
x=getfa(x);y=getfa(y);
if (x==y) return;
if (tr[x].dep>tr[y].dep)
{
while (tr[x].ch[0]) x=tr[x].ch[0];
tr[x].ch[0]=y;tr[y].fa=x;
splay(y,0);
}
else
{
while (tr[y].ch[1]) y=tr[y].ch[1];
tr[y].ch[1]=x;tr[x].fa=y;
splay(x,0);
}
}
void cut(int x)
{
splay(x,0);
tr[tr[x].ch[0]].fa=0;tr[x].ch[0]=0;
pushup(x);
}
ll query(int x,int y)
{
if (x==y) return 0;
int fx=getfa(x),fy=getfa(y);
if (fx!=fy) return -1;
splay(x,0);splay(y,x);
int ls=tr[y].ch[0],rs=tr[y].ch[1];
return get(y)?tr[ls].sum:tr[rs].sum;
}
bool vis[sz];
void debug(int x)
{
splay(x,0);
while (tr[x].ch[0]) x=tr[x].ch[0];
splay(x,0);
while (x&&tr[x].ch[1]) printf("%d<-",x),vis[x]=1,x=tr[x].ch[1];
printf("%d ",x);vis[x]=1;
}
int main()
{
// file();
int n,m,i,j,k,x,y,z;
read>>m;n=30000;
for (i=1;i<=n;i++) a[i]=1;
for (i=1;i<=n;i++) pushup(i);
while (m--)
{
char ch;cin>>ch;
if (ch=='M') read>>x>>y,connect(x,y);
else read>>x>>y,printf("%lld\n",query(x,y));
// for (i=1;i<=n;i++) if (!vis[i]) debug(i);
// puts("");memset(vis,0,sizeof(vis));
}
}