模板题,答案需要-1,三个村只需要两条路
cpp#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1000;
int father[maxn];
int find(int x) {
if (father[x] != x) {
father[x] = find(father[x]);
}
return father[x];
}
void unionn(int x, int y) {
int root_x = find(x);
int root_y = find(y);
if (root_x != root_y) {
father[root_x] = root_y;
}
}
int main() {
int n, m;
while (cin >> n >> m && n != 0) {
for (int i = 1; i <= n; ++i) {
father[i] = i;
}
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
unionn(a, b);
}
// Count the number of unique sets
int unique_sets = 0;
for (int i = 1; i <= n; ++i) {
if (father[i] == i) {
unique_sets++;
}
}
// Calculate the number of roads needed to connect all sets
int roads_needed = unique_sets - 1;
cout << roads_needed << endl;
}
return 0;
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!