Created
February 26, 2010 18:45
-
-
Save nhocki/316008 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <set> | |
using namespace std; | |
const int MAXN = 50005; | |
int p[MAXN]; | |
int find(int u){ | |
if (p[u] == u) return u; | |
return p[u] = find(p[u]); | |
} | |
void link(int u, int v){ | |
int a = find(u), b = find(v); | |
if (a != b){ | |
p[a] = b; | |
} | |
} | |
int main(){ | |
int n, m, C = 1; | |
while (scanf("%d %d", &n, &m) == 2){ | |
if (n == 0 and m == 0) break; | |
for (int i = 0; i < n; ++i) p[i] = i; | |
for (int i = 0; i < m; ++i){ | |
int u, v; | |
scanf("%d %d", &u, &v); | |
u--, v--; | |
link(u, v); | |
} | |
set<int> ans; | |
for (int i = 0; i < n; ++i) ans.insert(find(i)); | |
printf("Case %d: %d\n", C++, ans.size()); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <set> | |
using namespace std; | |
const int MAXN = 50005; | |
int p[MAXN]; | |
int find(int u){ | |
if (p[u] == u) return u; | |
return p[u] = find(p[u]); | |
} | |
void link(int u, int v){ | |
int a = find(u), b = find(v); | |
if (a != b){ | |
p[a] = b; | |
} | |
} | |
int main(){ | |
int n, m, C = 1; | |
while (scanf("%d %d", &n, &m) == 2){ | |
if (n == 0 and m == 0) break; | |
for (int i = 0; i < n; ++i) p[i] = i; | |
for (int i = 0; i < m; ++i){ | |
int u, v; | |
scanf("%d %d", &u, &v); | |
u--, v--; | |
link(u, v); | |
} | |
set<int> ans; | |
for (int i = 0; i < n; ++i) ans.insert(find(i)); | |
printf("Case %d: %d\n", C++, ans.size()); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment