【洛谷题解/AcWing题解/真题】洛谷P2330【SCOI2005】繁忙的都市(Kruskal算法的再探究))

题目链接

洛谷题解: https://www.luogu.com.cn/problem/P2330

AcWing题解: https://www.acwing.com/problem/content/1144/

涉及知识

最小生成树和 Kruskal 算法

思路分析

关于 Kruskal 算法,由于它是基于贪心算法的,所以有以下两种作用:

1. 求解最小边权和

2. 求解最大边权的最小值

因此对于本题,要想道路分值的最大值最小,就可以直接套 Kruskal 算法模板,不断更新 r e s res res 即可,最后更新加入的边,即最大边权,一定可以保证其最小。

AC代码

cpp 复制代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

const int N = 8100;

struct Edge
{
    int a, b, c;
    bool operator <(const Edge &W) const
    {
        return c < W.c;
    }
}edges[N];
int n, m, res;
int p[N];

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

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        edges[i] = {a, b, c};
    }
    
    sort(edges + 1, edges + m + 1);
    for (int i = 1; i <= n; i++) p[i] = i;
    for (int i = 1; i <= m; i++)
    {
        int a = edges[i].a, b = edges[i].b, c = edges[i].c;
        a = find(a), b = find(b);
        if (a != b)
        {
            p[a] = b;
            res = c;
        }
    }
    
    printf("%d %d", n - 1, res);
    return 0;
}
相关推荐
Nil2085 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
NeilYuen7 小时前
【C++】STL源码仿写(二):vector
开发语言·c++
郝学胜_神的一滴8 小时前
游戏引擎原理与实践 04:拆解引擎基础系统与内存管理
c++·游戏
wanderist.8 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.8 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
weixin_307779138 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
青少儿编程课堂8 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
倒头就睡的小比特8 小时前
C++多态
c++
光影少年9 小时前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
HEJOO99 小时前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法