基本思想:
无;
关键点:
无;
#include<iostream> #include<string> #include<vector> #include<map> using namespace std; const int maxn = 1020; int father[maxn]; int m, n; bool ma[maxn][maxn]; void init(int n) { for (int i = 0; i <= n; i++) father[i] = i; } int findfather(int x) { while (x != father[x]) { x = father[x]; } return x; } void unfather(int a, int b) { int aa = findfather(a); int bb = findfather(b); father[aa] = bb; } int cntnum(int n) { int cnt = 0; for (int i = 1; i <= n; i++) { if (father[i] == i) cnt++; } return cnt; } int main() { while (cin >> n >> m) { if (n == 0) continue; fill(ma[0], ma[0] + maxn * maxn, false); init(n); int a, b; for (int i = 0; i < m; i++) { cin >> a >> b; if (!ma[a][b]) { ma[a][b] = ma[b][a] = true; unfather(a, b); } } cout<<cntnum(n)-1<<endl; } return 0; }
原文地址:https://www.cnblogs.com/songlinxuan/p/12424144.html
时间: 2024-10-05 02:11:11