链接
https://vjudge.net/problem/UVA-11987
题解
这题是说在并查集原有的查询和合成的基础上,让你再支持一种把一个元素从一个集合拿出来放到另一个集合中的操作
其实我完全可以不去真的删除,而是开辟一个新的结点,并把原先的那个点的大小、权值都设为
0
0
0(相当于作废了)
然后用新开辟的点当真正的点
嗯…语言表达能力逐渐下降
代码
#include <bits/stdc++.h>
#define maxn 200010
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
typedef long long ll;
class MFS
{
private:
ll f[maxn], size[maxn], sum[maxn], now[maxn], tot;
public:
void init(ll n)
{
tot = n;
for(auto i=1ll;i<=n;i++)f[i]=i, size[i]=1, sum[i]=i, now[i]=i;
}
ll find(ll x){return x==f[x]?x:f[x]=find(f[x]);}
void merge(ll x, ll y)
{
auto fx=find(now[x]), fy=find(now[y]);
if(fx==fy)return;
f[fx]=fy;
size[fy] += size[fx];
sum[fy] += sum[fx];
}
void move(ll x, ll y)
{
auto fx=find(now[x]), fy=find(now[y]);
if(fx==fy)return;
size[fx]-=1, sum[fx]-=x;
now[x] = ++tot;
size[tot]=1, sum[tot]=x, f[tot]=tot;
merge(x,y);
}
void print_info(ll x)
{
auto fx=find(now[x]);
printf("%lld %lld\n",size[fx],sum[fx]);
}
}mfs;
ll read(ll x=0)
{
ll c, f=1;
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-48;
return f*x;
}
int main()
{
ll type, x, y, n, i, m;
while( ~scanf("%lld%lld",&n,&m) )
{
mfs.init(n);
while(m--)
{
type = read();
if(type==1 or type==2)x=read(), y=read();
else x=read();
if(type==1)
{
mfs.merge(x,y);
}
else if(type==2)
{
mfs.move(x,y);
}
else
{
mfs.print_info(x);
}
}
}
return 0;
}