栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

7-6 公路村村通 (30 分) | 最小生成树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

7-6 公路村村通 (30 分) | 最小生成树

#include 
#include 
using namespace std;

const int N = 1e3 + 10, M = 3 * N;
int n, m;   //nums of village, road
int p[N];   //父亲

struct Edge{
    int a, b, w;
    bool operator <(const Edge &tmp)const
    {
        return w < tmp.w;
    }
}edges[M];


//并查集
int find(int u)
{
    if(u != p[u]) p[u] = find(p[u]);
    return p[u];
}

int Kruskal()
{
    for(int i = 0; i < N; i++) p[i] = i;    //初始化并查集
    
    sort(edges, edges + m); //排序
    
    int res = 0, cnt = 0;
    for(int i = 0; i < m; i++)
    {
        int a = edges[i].a, b = edges[i].b, w = edges[i].w;
        a = find(a), b = find(b);
        if(a != b)  //未连通
        {
            p[b] = a;
            res += w;
            cnt ++;
        }
    }
    
    if(cnt < n - 1) return -1;
    else return res;
}

int main()
{
    //读取输入
    cin >> n >> m;
    for(int i = 0; i < m; i++)
        cin >> edges[i].a >> edges[i].b >> edges[i].w;
    
    cout << Kruskal();

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/676215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号