7-10 公路村村通(并查集kruskal)

最小生成树

题目链接

现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。

输入格式:
输入数据包括城镇数目正整数N(≤1000)和候选道路数目M(≤3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。

输出格式:
输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出−1,表示需要建设更多公路。

输入样例:

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3

输出样例:

12

C++代码

#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef long long ll;
const int N = 1e3 + 10;
const int M = 3 * N;
const int INF = 0x3f3f3f3f;
typedef pair<int,int> PII;
struct Edge{
    int u,v,w;
    bool operator<(const Edge &edge)const{
        return w < edge.w;
    }
}edge[M];
int fa[N],n,m;
void init(){
    for(int i = 0;i < n;i ++)fa[i] = i;
}
int Find(int x){
    return fa[x] = (x == fa[x] ? x : Find(fa[x]));	//压缩路径并查集
}
int main(){
    cin>>n>>m;
    init();
    int x,y,w;
    for(int i = 0;i < m;i ++){
        cin>>x>>y>>w;
        edge[i].u = x;
        edge[i].v = y;
        edge[i].w = w;
    }
    sort(edge,edge + m);
    int res = 0,cnt = 0;
    for(int i = 0;i < m;i ++){
        int X = Find(edge[i].u),Y = Find(edge[i].v);
        if(X != Y){
            fa[X] = Y;
            res += edge[i].w;
            cnt ++;
        }
    }
    if(cnt != n - 1)cout<< -1;
    else cout<<res;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值