acwing算法基础之搜索与图论--kruskal算法

目录

  • [1 基础知识](#1 基础知识)
  • [2 模板](#2 模板)
  • [3 工程化](#3 工程化)

1 基础知识

kruskal算法的关键步骤为:

  1. 将所有边按照权重从小到大排序。
  2. 定义集合S,表示生成树。
  3. 枚举每条边(a,b,c),起点a,终点b,边长c。如果结点a和结点b不连通(用并查集来维护),则将这条边加入到集合S中。

kruskal算法的时间复杂度为O(mlogm),它用来解决稀疏图的最小生成树问题。

2 模板

cpp 复制代码
int n, m;       // n是点数,m是边数
int p[N];       // 并查集的父节点数组

struct Edge     // 存储边
{
    int a, b, w;

    bool operator< (const Edge &W)const
    {
        return w < W.w;
    }
}edges[M];

int find(int x)     // 并查集核心操作
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int kruskal()
{
    sort(edges, edges + m);

    for (int i = 1; i <= n; i ++ ) p[i] = i;    // 初始化并查集

    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[a] = b;
            res += w;
            cnt ++ ;
        }
    }

    if (cnt < n - 1) return INF;
    return res;
}

3 工程化

题目1:求最小生成树。

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 2e5 + 10;
int p[N];
int n, m;

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

int find(int x) {
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < m; ++i) {
        cin >> edges[i].a >> edges[i].b >> edges[i].w;
    }
    
    //初始化并查集
    for (int i = 1; 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[a] = b;
            res += w;
            cnt ++;
        }
    }
    
    if (cnt < n-1) {
        cout << "impossible" << endl;
    } else {
        cout << res << endl;
    }
    
    return 0;
}
相关推荐
罗西的思考25 分钟前
【Agent】MemOS 源码笔记---(5)---记忆分类
人工智能·深度学习·算法
qq_433554543 小时前
C++数位DP
c++·算法·图论
AshinGau4 小时前
Softmax 与 交叉熵损失
神经网络·算法
似水এ᭄往昔4 小时前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
栀秋6664 小时前
“无重复字符的最长子串”:从O(n²)哈希优化到滑动窗口封神,再到DP降维打击!
前端·javascript·算法
xhxxx4 小时前
不用 Set,只用两个布尔值:如何用标志位将矩阵置零的空间复杂度压到 O(1)
javascript·算法·面试
有意义4 小时前
斐波那契数列:从递归到优化的完整指南
javascript·算法·面试
charlie1145141914 小时前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试
mmz12074 小时前
前缀和问题2(c++)
c++·算法
TL滕5 小时前
从0开始学算法——第十六天(双指针算法)
数据结构·笔记·学习·算法