kuangbin带你飞——专题六 最小生成树(4)

kuangbin带你飞——专题六 最小生成树(4)

专题网址:VJ网址 [kuangbin带你飞]专题1-23


题目来源:POJ 2421 Constructing Roads

VJ题目

题解

经典最小生成树题型。Kruskal 算法:

先讲各边从矩阵中提取出,再存边,将已经连通的边加入最小生成树,在按照边权值排序,在排序后依次选择边,如果这条边连接的点没有加入最小生成树,则加入,否则不加入。

AC代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;

const int maxn = 105;
// 存图
struct edge
{
    int u, v;
    int w;
    edge(int x, int y, int z) : u(x), v(y), w(z) {}
    bool operator<(const edge &B) const
    {
        return w < B.w;
    }
};
// 并查集维护连通性
int fa[maxn];
void init()
{
    for (int i = 1; i < maxn; ++i)
        fa[i] = i;
}
int find(int x)
{
    if (fa[x] == x)
        return x;
    fa[x] = find(fa[x]);
    return fa[x];
}
void unin(int x, int y)
{
    fa[find(x)] = find(y);
}

int main()
{
    int n;
    scanf("%d", &n);
    vector<edge> G;
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            int w;
            scanf("%d", &w);
            // 可以按照顺序存图
            if (j > i)
                G.push_back(edge(i, j, w));
        }
    }
    init();
    int m, ans = 0;
    scanf("%d", &m);
    for (int i = 1; i <= m; ++i)
    {
        int u, v;
        scanf("%d%d", &u, &v);
        unin(u, v);
    }
    // 排序
    sort(G.begin(), G.end());
    // 遍历
    vector<edge>::iterator it;
    for (it = G.begin(); it != G.end(); ++it)
    {
        int u = it->u, v = it->v;
        if (find(u) != find(v))
        {
            ans += it->w;
            unin(u, v);
        }
    }
    printf("%d", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值