From e5bb7ab971194a0f2e608ddf55314cdb3c76c04c Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Thu, 25 Jul 2024 20:20:35 +0800 Subject: [PATCH] =?UTF-8?q?P1111=20=E4=BF=AE=E5=A4=8D=E5=85=AC=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/168121919 --- Luogu/P1111/P1111.cpp | 69 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Luogu/P1111/P1111.cpp diff --git a/Luogu/P1111/P1111.cpp b/Luogu/P1111/P1111.cpp new file mode 100644 index 00000000..3de91e30 --- /dev/null +++ b/Luogu/P1111/P1111.cpp @@ -0,0 +1,69 @@ +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1e3 + 5, + M = 1e5 + 5; + +int n, m; +int cnt, fa[N]; // cnt: number of connected components + +struct node { + int x, y, t; +} a[M]; + +int find(int x) { + return fa[x] == x ? x : fa[x] = find(fa[x]); +} + +void merge(int x, int y) { + x = find(x); + y = find(y); + + if (x != y) { + fa[x] = y; + cnt--; + } +} + +bool cmp(const node &a, const node &b) { + return a.t < b.t; +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n >> m; + + // 初始化并查集 + cnt = n; + + for (int i = 1; i <= n; i++) { + fa[i] = i; + } + + for (int i = 1; i <= m; i++) { + cin >> a[i].x >> a[i].y >> a[i].t; + } + + std::sort(a + 1, a + 1 + m, cmp); + + for (int i = 1; i <= m; i++) { + merge(a[i].x, a[i].y); + + if (cnt == 1) { + cout << a[i].t << endl; + + exit(0); + } + } + + // 无解 + cout << -1 << endl; + + return 0; +}