题解:SP5150 JMFILTER - Junk-Mail Filter

· · 题解

算法

可删并查集。

思路:

那么,如何维护可删并查集呢?

合并、查询操作:

int find(int x){
    return (fa[x]==x?x:fa[x]=find(fa[x]));
}
void un(int x,int y){
    x=find(x),y=find(y);
    if(x!=y)fa[x]=y;
}

这个和普通的一样,不在赘述。

删除:

void del(int x){
    fa[x]=++p;//p即垃圾桶
}

并查集的思路可以看作每一个节点一开始都在各自一个独立的盒子内,删除只需将节点放入一个垃圾桶内,因为节点间是由盒子确定的,所以这样删除并不会影响关系。

所以就得到了正解。

代码:

#include<bits/stdc++.h>
using namespace std;
#define I_love return
#define in(a) a=read()
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define deap(i,a,b) for(int i=b;i>=a;i--)
#define pii pair<int,int>
#define mk(a,b) make_pair(a,b)
#define fi first
#define se second
#define pd(a) push_back(a)
#define Firefly 0;
#define int long long
const int N = 3e6 + 5;
const int inf = INT_MAX;
inline int read(){
    int ch=getchar(),f=1,x=0;
    while('9'<ch||ch<'0'){
        if(ch=='-')f=-1;
        ch=getchar();
    }
    while('0'<=ch&&ch<='9'){
        x=x*10+ch-'0';
        ch=getchar();
    }
   return x*f;
}
void fast() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}
int n,m;
int p;
int fa[N];
int find(int x){
    return (fa[x]==x?x:fa[x]=find(fa[x]));//查询
}
void un(int x,int y){
    x=find(x),y=find(y);
    if(x!=y)fa[x]=y;//合并
}
void del(int x){
    fa[x]=++p;//将x放入垃圾桶中
}
void init(){
    rep(i,1,n){
        fa[i]=i+n;
    }
    rep(i,n+1,p+m/*可能m个操作均为删除,所以初始化要到p+m*/){
        fa[i]=i;
    }
}
unordered_set<int >s;
signed main(){
    fast();
    int pp=0;
    while(1){
        pp++;
        cin>>n>>m;
        if(n==0&&m==0)break;//m可以等于0!!!
        p=2*n;//开垃圾桶
        init();
        rep(i,1,m){
            char op;
            cin>>op;
            if(op=='M'){
                int x,y;
                cin>>x>>y;
                un(++x,++y);//合并
            }else{
                int x;
                cin>>x;
                del(++x);//删除
            }
        }
        s.clear(); 
        rep(i,1,n){
            s.insert(find(i)); //使用集合维护答案
        }
        printf("Case #%lld: %lld\n",pp,s.size());
    }
    I_love Firefly;
}