以上共两种方法,均可以AC,并查集
001./*#include <iostream>
002.
#include <stdio.h>
003.
#include <stdlib.h>
004.
#include <string.h>
005.
#include <math.h>
006.
#include <algorithm>
007.
#include <stack>
008.
#include <queue>
009.
#include <map>
010.
using namespace std;
011.
012.
int f[1005];
013.
int e[1005];
014.
int vis[1005];
015.
016.
int findset(int a)
017.
{
018.
if(a == f[a])
019.
{
020.
return a;
021.
}
022.
f[a] = findset(f[a]);
023.
return f[a];
024.
025.
}
026.
void unionset(int a,int b)
027.
{
028.
a = findset(a);
029.
b = findset(b);
030.
if(a!=b)
031.
{
032.
f[b] = a;
033.
}
034.
}
035.
int main()
036.
{
037.
/*#ifndef ONLINE_JUDGE
038.
freopen("in.txt","r",stdin);
039.
#endif*/
040.
/* int n,m;
041.
char c;
042.
int a,b;
043.
while(scanf(" %d %d",&n,&m)!=EOF)
044.
{
045.
memset(e,0,sizeof(e));
046.
memset(vis,0,sizeof(vis));
047.
048.
for(int i=1; i<=n; i++)
049.
{
050.
f[i] = i;
051.
}
052.
for(int i=0; i<m; i++)
053.
{
054.
scanf(" %c %d %d",&c,&a,&b);
055.
//printf("c = %c\n",c);
056.
if(c == 'F')
057.
{
058.
unionset(a,b);
059.
}
060.
else if(c == 'E')
061.
{
062.
if(e[a] == 0)
063.
{
064.
e[a] = b;
065.
}
066.
else
067.
{
068.
unionset(e[a],b);
069.
}
070.
if(e[b] == 0)
071.
{
072.
e[b] = a;
073.
}
074.
else
075.
{
076.
unionset(e[b],a);
077.
}
078.
}
079.
}
080.
int sum = 0;
081.
for(int i=1; i<=n; i++)
082.
{
083.
int cur = findset(i);
084.
if(vis[cur] == 0)
085.
{
086.
vis[cur] = 1;
087.
sum++;
088.
}
089.
}
090.
printf("%d\n",sum);
091.
}
092.
return 0;
093.
}*/
094.
095.
096.
097.
098.
099.
100.
101.
102.
#include<cstdio>
103.
#include<cstdlib>
104.
#include<cstring>
105.
#include<algorithm>
106.
#include<cmath>
107.
#include<iostream>
108.
using
namespace
std;
109.
110.
int
n,m;
111.
const
int
maxn=1000;
112.
int
f[maxn+10],e[maxn+10];
113.
114.
int
find(
int
x)
115.
{
116.
if
(f[x]==x)
return
f[x];
117.
f[x]=find(f[x]);
118.
return
f[x];
119.
}
120.
121.
void
together(
int
a,
int
b)
122.
{
123.
int
aa=find(a),bb=find(b);
124.
f[aa]=f[bb];
125.
}
126.
127.
int
main()
128.
{
129.
//freopen("input.txt","r",stdin);
130.
//freopen("output.txt","w",stdout);
131.
scanf
(
"%d%d"
,&n,&m);
132.
for
(
int
i=1; i<=n; i++)
133.
f[i]=i;
134.
135.
while
(m--)
136.
{
137.
char
flag=(
getchar
(),
getchar
());
138.
int
a,b;
139.
scanf
(
"%d%d"
,&a,&b);
140.
if
(flag==
'F'
) together(a,b);
141.
else
142.
{
143.
if
(!e[a]) e[a]=b;
144.
else
together(e[a],b);
145.
if
(!e[b]) e[b]=a;
146.
else
together(e[b],a);
147.
}
148.
}
149.
150.
int
ans=0;
151.
for
(
int
i=1; i<=n; i++)
152.
if
(f[i]==i) ans++;
153.
154.
printf
(
"%d\n"
,ans);
155.
fclose
(stdin);
156.
fclose
(stdout);
157.
return
0;
158.
}