注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998Huge input, scanf is recommended.HintHint
并查集模板题。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
int n, m, par[1010];
int find(int x)
{
if(par[x] == x) return x;
else return par[x] = find(par[x]);
}
void unite(int x, int y)
{
x = find(x);
y = find(y);
if(x == y) return;
par[y] = x;
}
void init()
{
for(int i = 1; i <= n; ++i)
par[i] = i;
}
int main(int argc, char const *argv[])
{
while(scanf("%d%d", &n, &m) != EOF) {
if(n == 0) break;
init();
for(int i = 0; i < m; ++i) {
int a, b;
scanf("%d%d", &a, &b);
unite(a, b);
}
int ans = 0;
for(int i = 1; i <= n; ++i)
if(par[i] == i) ans++;
printf("%d\n", ans - 1);
}
return 0;
}
619



被折叠的 条评论
为什么被折叠?



