#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
int g[1001];
int e[1001];
int n,m;
int find(int i)
{
return g[i]==i?i:g[i]=find(g[i]);
}
int main()
{
scanf("%d%d\n",&n,&m);
for(int i = 1;i <= n;++i)g[i]=i;
char c;
int p,q;
for(int i = 1; i < m;++i)
{
scanf("%c%d%d\n",&c,&p,&q);
if(c=='F')
{
int x = find(p);
int y = find(q);
g[x]=y;
}
else
{
if(e[p])
{
g[find(e[p])]=find(q);
}
else
{
e[p]=q;
}
if(e[q])
{
g[find(e[q])]=find(p);
}
else
{
e[q]=p;
}
}
}
scanf("%c%d%d",&c,&p,&q);
if(c=='F')
{
int x = find(p);
int y = find(q);
g[x]=y;
}
else
{
if(e[p])
{
g[find(e[p])]=find(q);
}
else
{
e[p]=q;
}
if(e[q])
{
g[find(e[q])]=find(p);
}
else
{
e[q]=p;
}
}
int ans(0);
for(int i = 1;i <= n;++i)
{
if(find(i)==i) ++ans;
}
cout << ans;
return 0;
}
以上是郭神的代码。。不忍吐槽。。
以下是我的↓
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int n,m;
int fa[1001],f[1001];
int find(int t)
{
if(fa[t]==t)return t;
return fa[t]=find(fa[t]);
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)fa[i]=i;
char c;
int x,y;
for(int i=1;i<=m;i++)
{
scanf("\n %c%d%d",&c,&x,&y);
if(c == 'F')
{
int fx = find(x);
int fy = find(y);
if(fx!=fy)fa[fy]=fx;
}
else
{
if(f[x])
fa[find(f[x])]=find(y);
else
f[x]=y;
if(f[y])
fa[find(f[y])]=find(x);
else
f[y]=x;
}
}
int ans=0;
for(int i=1;i<=n;i++)
{
if(find(i) == i)ans++;
}
printf("%d",ans);
return 0;
}