暴力水过
朋友就合并,敌人就存下来再把它的敌人两两合并。
似乎可以拆点?
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char opt[1];
int n,m,sum,cnt,f[1005],head[1005],ans[1005],next[10005],list[10005];
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline void insert(int x,int y)
{
next[++cnt]=head[x];
head[x]=cnt;
list[cnt]=y;
}
int find(int i)
{
return f[i]==i?i:f[i]=find(f[i]);
}
int main()
{
n=read(); m=read();
for (int i=1;i<=n;i++) f[i]=i;
for (int i=1;i<=m;i++)
{
scanf("%s",opt);
int x=read(),y=read(),p=find(x),q=find(y);
if (opt[0]=='F') f[p]=q;
else insert(x,y),insert(y,x);
}
for (int x=1;x<=n;x++)
for (int i=head[x];i;i=next[i])
for (int j=next[i];j;j=next[j])
{
int p=find(list[i]),q=find(list[j]);
if (p!=q) f[p]=q;
}
for (int i=1;i<=n;i++) ans[i]=find(i);
sort(ans+1,ans+n+1);
for (int i=1;i<=n;i++)
if (ans[i]!=ans[i-1]) sum++;
cout << sum;
return 0;
}