Problem Description
海上有N
(1<= N <=2000)
个岛,编号从1到N,同一部落的岛屿之间有直接或间接的路相连,不同部落之间无路可通。现在给出M
(1<= M <= N*(N-1)/2)
条路。问这片海域上共有多少部落。
Input
多组输入。每组第一行输入N,M。接下来M行每行,每行两个整数u,v代表岛u与v之间有一条路。
Output
每组数据输出一个整数,代表部落数。
Example Input
3 1 1 2 3 2 1 2 1 3
Example Output
2 1
Hint
Author
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5 +5;
const int INF = 0x3f3f3f3f;
int pre[maxn], deep[maxn], n[maxn];
int Find(int x) {
return pre[x] == x ? x : Find(pre[x]);
}
void Unite(int x, int y) {
x = Find(x);
y = Find(y);
if(x == y) {
return;
}
if(deep[x] < deep[y]) {
pre[x] = y;
} else {
pre[y] = x;
if(deep[x] == deep[y]) {
deep[x]++;
}
}
}
void CSH(ll k) {
memset(deep, 0, sizeof(deep));
memset(n, 0, sizeof(n));
for(int i = 1; i <= k; i++) {
pre[i] = i;
}
}
void SR(ll m) {
for(int i = 1; i <= m; i++) {
ll x, y;
scanf("%d%d", &x, &y);
n[x] = n[y] = 1;
Unite(x, y);
}
}
void SC(ll n) {
int ans = 0;
for(int i = 1; i <= n; i++) {
if(pre[i] == i) {
ans++;
}
}
printf("%d\n", ans);
}
int main() {
ll n, m;
while(~scanf("%lld%lld", &n, &m)) {
CSH(n);
SR(m);
SC(n);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 16ms
Take Memory: 1728KB
Submit time: 2018-02-01 10:23:28
****************************************************/