#include <stdio.h> #include <stdlib.h> #include <memory.h> int father[10005]; bool arr[10005]; void init () { for (int i=0; i<1000; i++) { father[i] = i; } } int find (int x) {//查找并压缩路径 return father[x] == x ? x : father[x] = find(father[x]); } void join (int x, int y) { int p1 = find(x); int p2 = find(y); if (p1 == p2) { return; } father[p1] = p2; } bool check (int x, int y) { int p1 = find(x); int p2 = find(y); if (p1 == p2) { return true; } else { return false; } } int main (int argc, char **argv) { int m, n; int a, b; int ans; while (scanf("%d",&m)) {//m城镇,n道路 if (m == 0) { break; } scanf("%d", &n); init(); ans = 0; for (int i=1; i <= n; i++) { scanf("%d %d", &a, &b); join(a, b); } memset(arr, 0, sizeof(arr)); for (int i=1; i <= m; i++) { arr[find(i)] = 1; } for (int i=1; i <= m; i++) { if (arr[i]) { ans++; } } printf("%d\n", ans - 1); } return 0; }
数据结构:并查集
猜你喜欢
转载自blog.csdn.net/thelostlamb/article/details/79455798
今日推荐
周排行