支持删除的并查集 hdu2473
题解:
代码:
#include<bits/stdc++.h> using namespace std; #define ll long long const int maxn=5000050; int fa[maxn],id,vis[maxn]; int find(int x) { if (x!=fa[x]) fa[x]=find(fa[x]); return(fa[x]); } void merge(int x,int y) { int fx=find(x),fy=find(y); if (fx!=fy) fa[fx]=fy; } void del(int x) { fa[x]=++id; } int main() { freopen("noip.in","r",stdin); freopen("noip.out","w",stdout); int n,m,Case=0; while (scanf("%d%d",&n,&m),n+m) { for (int i=1;i<=n;i++) fa[i]=i+n; for (int i=n+1;i<=n+n+m;i++) fa[i]=i; id=n+n; int a,b;char ch[5]; for (int i=1;i<=m;i++) { cin>>ch; if (ch[0]=='M') { cin>>a>>b; merge(a,b); } else { cin>>a; del(a); } } int ans=0; memset(vis,0,sizeof(vis)); for (int i=1;i<=n;i++) { int x=find(i); if (!vis[x]) ans++,vis[x]=1; } printf("Case #%d: %d\n",++Case,ans); } return 0; }