POJ 2421 Constructing Roads

本文介绍了一种基于Kruskal算法实现最小生成树的具体过程。通过输入矩阵来构造图,并利用排序和并查集确定最小生成树的边,最终输出最小生成树的总权重。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:
[kuangbin带你飞]专题六 最小生成树 D - Constructing Roads

输入矩阵,求最小生成树。其中有的边已经联通,不需要再计算,将其权值置为0即可。

//#include"stdafx.h"
#include <iostream>
#include <cstdio>
#include <cmath>
#include<cstring>
#include <algorithm>
using namespace std;

struct edge
{
    int s, e, w;
};

edge e[10008];
int p[108];
int n, ans = 0, cnt = 0;
int map[108][108];

bool cmp(edge a, edge b) { return a.w < b.w; }
int find(int x){ return x == p[x] ? x : p[x] = find(p[x]); }

void kruscal()
{
    sort(e, e + cnt, cmp);

    for (int i = 0; i < cnt; i++)
    {
        int x = find(e[i].s);
        int y = find(e[i].e);
        if (x != y)
        {
            p[x] = y;
            ans += e[i].w;
        }
    }
    cout << ans << endl;
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) cin >> map[i][j];

    int m, x, y;
    for (int i = 0; i <= n; i++) p[i] = i;

    cin >> m;
    for (int i = 0; i < m; i++)
    {
        cin >> x >> y;
        //ans += map[x - 1][y - 1];
        map[x - 1][y - 1] = 0;
    }



    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            {
                e[cnt].s = i;
                e[cnt].e = j;
                e[cnt++].w = map[i][j];
            }

    kruscal();

    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值