<题目链接>
题目大意:
利用并查集找出图中有几个不连通的城镇集合,所需修的道路数即为城镇集合-1。
#include <stdio.h> int pre[1005]; int find(int x) { int r = x; while (pre[r] != r) r = pre[r]; int i = x; int j; while (pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r; } void join(int a,int b) { int f1 = find(a); int f2 = find(b); if (f1 != f2) { pre[f2] = f1; } } int main() { int n, m, i, j,ans,a,b; while (scanf("%d%d", &n, &m) != EOF, n) { for (i = 1; i <= n; i++)pre[i] = i; for (i = 0; i < m; i++) { scanf("%d%d", &a, &b); join(a, b); } ans = 0; for (i = 1; i <= n; i++) { if (pre[i] == i)ans++; //记录下这个图中有几个联通分支 } printf("%d ", ans - 1); }//联通所需的道路就是联通分支数-1 return 0; }
2018-04-02