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

畅通工程 -并查集

#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;
}

 

 

相关文章:

  • 2021-09-24
  • 2021-08-23
  • 2021-09-27
  • 2021-06-11
  • 2022-12-23
  • 2021-07-12
  • 2022-03-06
  • 2022-02-15
猜你喜欢
  • 2021-07-02
  • 2022-12-23
  • 2022-12-23
  • 2021-05-24
  • 2021-06-24
  • 2021-08-08
  • 2022-01-22
相关资源
相似解决方案