来源:
今天在安静的草坪上写这些东西,相对于其他地方,心理能够宁静下来许多,就是稍微有点冷了。
带删除的并查集。方法是将初始化father[i]=i的,用数组代替,这样可以回溯到删除时的初始状态了。
时间卡的略微拙计。
#include <iostream>
#include <cstring>
#include <set>
#include <cstdio>
#include <algorithm>
using namespace std;
const int M=2000005;
int father[M],rank[M],flag[M];
int n,m;
int res;
void init()
{
for(int x=0;x<M;x++)
{
father[x]=x;
rank[x]=1;
flag[x]=x;
}
}
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
void Union(int x,int y)
{
x=find(x);
y=find(y);
if(x==y)
return;
if(rank[x]>rank[y])
{
father[y]=x;
rank[x]+=rank[y];
}
else
{
father[x]=y;
rank[y]+=rank[x];
}
res--;
}
bool Delete(int x)
{
int a=find(x);
if(rank[a]>1)
{
res++;
--rank[a];
return 1;
}
return 0;
}
int main()
{
int n,m;
int tenum=1;
while(cin>>n>>m)
{
if(n==0&&m==0)
return 0;
init();
res=n;
set<int> s;
for(int i=0;i<m;i++)
{
char c;
cin>>c;
if(c=='M')
{
int a,b;
cin>>a>>b;
Union(flag[a],flag[b]);
}
if(c=='S')
{
int a;
cin>>a;
if(Delete(flag[a]))
{
flag[a]=++n;
}
}
}
printf("Case #%d: %d\n",tenum++,res);
}
return 0;
}