#include "bits/stdc++.h"
using namespace std;
class UnionFind {
vector<int> parent, rank;
int time;
int count;
public:
UnionFind(int N)
: parent(N), rank(N), count(N)
{
time = 0;
for (int i = 0; i < N; i++) {
parent[i] = i;
rank[i] = 1;
}
}
int find(int node)
{
if (node == parent[node])
return node;
return parent[node]
= find(parent[node]);
}
void performUnion(int u, int v,
int updatedTime)
{
if (count == 1)
return;
int rootX = find(u);
int rootY = find(v);
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
}
else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
}
else {
parent[rootX] = rootY;
rank[rootY] += 1;
}
time = updatedTime;
count--;
}
}
int getCount() { return count; }
int getTime() { return time; }
};
bool cmp(vector<int>& A, vector<int>& B)
{
return A[2] <= B[2];
}
int earliestTime(vector<vector<int> >& arr,
int N)
{
sort(arr.begin(), arr.end(), cmp);
UnionFind unionFind(N);
for (auto& it : arr) {
unionFind.performUnion(
it[0], it[1], it[2]);
}
if (unionFind.getCount() == 1) {
return unionFind.getTime();
}
else {
return -1;
}
}
int main()
{
int N = 6;
vector<vector<int> > arr
= { { 0, 1, 4 }, { 3, 4, 5 },
{ 2, 3, 14 }, { 1, 5, 24 },
{ 2, 4, 12 }, { 0, 3, 42 },
{ 1, 2, 41 }, { 4, 5, 11 } };
cout << earliestTime(arr, N);
return 0;
}