#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class DSU {
public:
    vector<int> size;
    vector<int> parent;

    DSU(int n) {
        size.assign(n, 1);
        parent.resize(n);
        for (int i = 0; i < n; i++) parent[i] = i;
    }

    int findParent(int x) {
        if (x == parent[x]) return x;
        return parent[x] = findParent(parent[x]); // Path compression
    }

    void unionBySize(int x, int y) {
        int rootX = findParent(x); // FIX: Must use findParent
        int rootY = findParent(y);
        if (rootX != rootY) {
            if (size[rootX] < size[rootY]) swap(rootX, rootY);
            parent[rootY] = rootX;
            size[rootX] += size[rootY];
        }
    }
};

int maxWeightInGraph(int threshold, vector<vector<int>> edges, int n) {
    // If threshold is 0 and we have more than 1 node, it's impossible
    if (threshold < 1 && n > 1) return -1;

    // 1. Sort edges by weight (Ascending)
    sort(edges.begin(), edges.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[2] < b[2];
    });

    DSU dsu(n);
    int maxW = -1;

    // 2. Greedy merge (Kruskal's logic)
    for (const auto& edge : edges) {
        int u = edge[0];
        int v = edge[1];
        int w = edge[2];

        // We unite the nodes. In the context of reachability to 0, 
        // we treat the connection as an undirected bridge.
        dsu.unionBySize(u, v);
        maxW = w;

        // 3. Check if all nodes are now in the same component as Node 0
        // findParent(0) will give the root of the component containing 0.
        // If that component's size is N, everyone can reach 0.
        if (dsu.size[dsu.findParent(0)] == n) {
            return maxW;
        }
    }

    return -1; // Not all nodes could be connected
}

int main() {
    // Example 1
    vector<vector<int>> edges1 = {{1,0,2},{2,1,3},{2,3,3}};
    cout << "Example 1 (Expected 1): " << maxWeightInGraph(2, edges1, 4) << endl;

    // Example 2
    vector<vector<int>> edges2 = {{0,1,1},{0,2,2},{0,3,1},{0,4,1},{1,2,1},{1,4,1}};
    cout << "Example 2 (Expected -1): " << maxWeightInGraph(1, edges2, 5) << endl;

    return 0;
}