最小生成树模板(Krustral)

本文展示了一个C++程序,该程序利用Kruskal算法来找到图的最小生成树。程序读取边的数量和节点,然后通过排序边的权重并应用并查集来避免形成环路,最终输出最小生成树的总权重。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <fstream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 1024;
typedef struct Node
{
    int s, e, val;
    Node(int a, int b, int c)
    {
        s = a, e = b, val = c;
    }
    bool operator < (const Node& p) const
    {
        return p.val > val;
    }
};
vector<Node> q;
int p[N];
int find(int x)
{
    return x == p[x]? x:find(p[x]);
}
int main(void)
{

    int kase;
    cin>>kase;
    while(kase--)
    {
        int n, s;       //n个点, s条边
        cin>>n>>s;
        //初始化父节点
        for(int i = 0; i < n; i++)
            p[i] = i;
        for(int i = 0; i < s; i++)
        {
            int x, y, w;    //x起点 y终点 w权值
            cin>>x>>y>>w;
            q.push_back(Node(x, y, w));
        }
        sort(q.begin(), q.end());
        int s
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值