题目描述:任意两个城镇间都可以实现交通(不一定直接连接),问最少雪妖建设多少条路

#include<iostream>
#include<string.h>
#include<string>
#include<math.h>
using namespace std;
int path[1000];
int findroot(int x,int *a)
{
if (a[x] == -1)
return x;
else {
int tmp = findroot(a[x],a);
a[x] = tmp;
return tmp;
}
}
int main(){
int m, n, a, b;
while (cin >> n&&n!=0)
{
cin >> m;
for (int i = 1; i <= n; i++)
path[i] = -1;
while (m--)
{
cin >> a >> b;
a = findroot(a,path);
b = findroot(b, path);
if (a != b) path[a] = b;
}
int res = 0;
for (int i = 1; i <= n; i++)
if (path[i] == -1)
res++;
cout << res-1 << endl;
}
return 0;
}
本文通过一个具体的案例,介绍了一种求解最小生成树问题的方法。该算法利用并查集来处理图中边的关系,有效地找出使所有节点连通所需的最少边数。
599

被折叠的 条评论
为什么被折叠?



