跳到正文

题解

题解:P12222 [蓝桥杯 2023 国 Java B] 电动车

popcount约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年4月20日
收录
2025年12月12日
更新
2026年11月22日
篇幅
约 5 分钟
获赞
1
题目
P12222

版本

  1. v1当前

题解:P12222 [蓝桥杯 2023 国 Java B] 电动车

这道题为什么会想到要用 Kruskal 呢?因为标签里有。

首先,题目要求一张无向连通图的最大边权的最小值。

而我们可以把边权从小到大排序,然后对于每条边,如果边连接的两个点已经连通,那么就忽略;否则把这两条边连接,那这时就多了一条边。

一个 nn 个点的无向连通图至少有 n−1n - 1 条边,那选到第 n−1n - 1 条边时这条边的边权就是答案了,因为边权已经从小到大排序了。

好了思路分析完了就可以一眼 Kruskal 了,纯板子题。

C++ 代码如下:

C++
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;

int n, m;
int f[200010];

struct edge {
    int u, v, w;
} g[200010];

int find(int u) {
    return u == f[u] ? u : f[u] = find(f[u]);
}

int main() {
    cin >> n >> m;
    for (int i = 1, u, v, w; i <= m; i++) {
        cin >> g[i].u >> g[i].v >> g[i].w;
    }
    sort(g + 1, g + m + 1, [&](edge& x, edge& y) {
        return x.w < y.w;
    }) ;
    int tot = 0;
    iota(f + 1, f + n + 1, 1);
    for (int i = 1; i <= m; i++) {
        int x = find(g[i].u), y = find(g[i].v);
        if (x != y) {
            f[x] = y;
            tot++;
            if (tot == n - 1) {
                cout << g[i].w << endl;
                return 0;
            }
        } 
    }
    cout << -1 << endl;
    return 0;
}

AC Record


Java 代码如下:

Java
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static int n, m;
    static int[] f = new int[200010];

    static class Edge {
        int u, v, w;

        Edge(int u, int v, int w) {
            this.u = u;
            this.v = v;
            this.w = w;
        }
    }

    static Edge[] g = new Edge[200010];

    static int find(int u) {
        if (u == f[u]) {
            return u;
        } else {
            f[u] = find(f[u]);
            return f[u];
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        m = scanner.nextInt();
        for (int i = 1; i <= m; i++) {
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            int w = scanner.nextInt();
            g[i] = new Edge(u, v, w);
        }
        Arrays.sort(g, 1, m + 1, (x, y) -> Integer.compare(x.w, y.w));
        int tot = 0;
        for (int i = 1; i <= n; i++) {
            f[i] = i;
        }
        for (int i = 1; i <= m; i++) {
            int x = find(g[i].u);
            int y = find(g[i].v);
            if (x != y) {
                f[x] = y;
                tot++;
                if (tot == n - 1) {
                    System.out.println(g[i].w);
                    return;
                }
            }
        }
        System.out.println(-1);
    }
}

AC Record

原文