【题目链接】
https://www.lydsy.com/JudgeOnline/problem.php?id=1370
【算法】
并查集 + 拆点
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 1010 int i,n,m,x,y,cnt; char opt[5]; int a[MAXN]; class DisjointSet { private : int s[MAXN<<1]; public : inline void init(int n) { int i; for (i = 1; i <= n; i++) s[i] = i; } inline int get_root(int x) { if (s[x] == x) return x; return s[x] = get_root(s[x]); } inline void merge(int x,int y) { s[get_root(x)] = get_root(y); } } S; int main() { scanf("%d%d",&n,&m); S.init(n<<1); for (i = 1; i <= m; i++) { scanf("%s%d%d",&opt,&x,&y); if (opt[0] == 'F') S.merge(x,y); else { S.merge(x,y+n); S.merge(y,x+n); } } for (i = 1; i <= n; i++) a[i] = S.get_root(i); sort(a+1,a+n+1); for (i = 1; i <= n; i++) { if (a[i] != a[i-1]) cnt++; } printf("%d ",cnt); return 0; }