#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5 , M = 1e3 + 5;
int n , m , maxt = -1;
int a[N] , x[M] , y[M] , t[M];
void init(){
for(int i = 1 ; i <= N ; i++){
a[i] = i;
}
}
int find(int x){
if(x == a[x]) return x;
return a[x] = find(a[x]);
}
int main(){
cin >> n >> m;
init();
for(int i = 1 ; i <= m ; i++){
cin >> x[i] >> y[i] >> t[i];
maxt = max(maxt , t[i]);
}
for(int i = 1 ; i <= maxt ; i++){
for(int j = 1 ; j <= m ; j++){
if(t[j] == i){
a[find(x[j])] = find(y[j]);n--;
}
}
if(n == 1) return cout << i , 0;
}
cout << "-1";
return 0;
}