解题思路:
并查集。Find 递归跑得比循环慢一点。
参考代码:
#include<bits/stdc++.h> using namespace std; int pre[1003], point; int find(int ele) { return ele == pre[ele] ? ele : pre[ele] = find(pre[ele]); } void link(int elest, int elend) { int findst = find(elest), findnd = find(elend); if (findst != findnd) pre[findst] = findnd; } void init(int point) { for (int i = 0; i < point; i++) pre[i] = i; } int main() { int paths, poi1, poi2; while (cin >> point && point && cin >> paths) { init(point); while (paths--) { cin >> poi1 >> poi2; link(poi1, poi2); } int total = 0; for (int i = 0; i < point; i++) if (pre[i] == i) total++; cout << total - 1 << endl; } }
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题11.3 (C语言代码)浏览:1052 |
C语言程序设计教程(第三版)课后习题9.3 (Java代码)浏览:956 |
C语言程序设计教程(第三版)课后习题7.4 (C语言代码)浏览:604 |
【回文数(二)】 (C语言代码)浏览:728 |
C语言程序设计教程(第三版)课后习题9.6 (C语言代码)浏览:277 |
C语言程序设计教程(第三版)课后习题10.2 (C语言代码)浏览:535 |
C语言程序设计教程(第三版)课后习题11.3 (C语言代码)浏览:2158 |
母牛的故事 (C语言代码)浏览:476 |
开门人和关门人浏览:1125 |
字符串比较 (C语言代码)浏览:1220 |