解题思路:
并查集。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.8 (C语言代码)浏览:884 |
C语言程序设计教程(第三版)课后习题8.9 (C语言代码)浏览:832 |
printf基础练习2 (C语言代码)浏览:618 |
文科生的悲哀 (C语言代码)浏览:1401 |
A+B for Input-Output Practice (VI) (C语言代码)浏览:558 |
核桃的数量 (C语言代码)浏览:872 |
勾股数 (C语言代码)浏览:799 |
C语言训练-8除不尽的数 (C语言代码)浏览:1402 |
矩阵转置 (C语言代码)浏览:783 |
C语言程序设计教程(第三版)课后习题11.5 (C语言代码)浏览:999 |