#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int64_t n, m;
  cin >> n >> m;
  vector<pair<int64_t, pair<int64_t, int64_t> > > a(m);
  int64_t kol = 0;
  map<int64_t, int64_t> us;
  for (int64_t i = 0; i < m; i++) {
    cin >> a[i].second.first >> a[i].second.second >> a[i].first;
    if (us[a[i].first] == 0) {
      kol++;
      us[a[i].first] = 1;
    }
  }
  if (kol == 1 || kol == 9 && m == 9) {
    cout << -1;
    return 0;
  }
  sort(a.begin(), a.end());
  set<int64_t> s1, s2;
  for (int64_t i = 0; i < m; i++) {
    s1.insert(a[i].second.first);
    s2.insert(a[i].second.second);
    if (s1.size() == n && s2.size() == n && s1.size() != 1) {
      cout << a[i].first << '\n';
      return 0;
    }
  }
  cout << -1;
}
