#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
struct node {
  int u, v;
};
map<int, queue<node> > mp;
int a[maxn], b[maxn];
int main() {
  int i, n, m, u, v, d;
  bool flag = 1;
  cin >> n >> m;
  for (i = 0; i < m; i++) {
    scanf("%d%d%d", &u, &v, &d);
    mp[d].push((node){u, v});
    a[u]++;
    b[v]++;
  }
  for (i = 1; i <= n; i++) {
    if (a[i] == 0 || b[i] == 0) {
      flag = 0;
      break;
    }
  }
  int ans;
  if (!flag) {
    cout << -1;
  } else {
    map<int, queue<node> >::reverse_iterator it;
    for (it = mp.rbegin(); it != mp.rend(); it++) {
      ans = it->first;
      while (!(it->second).empty()) {
        a[(it->second).front().u]--;
        b[(it->second).front().v]--;
        if (a[(it->second).front().u] == 0 || b[(it->second).front().v] == 0) {
          flag = 0;
          break;
        }
        (it->second).pop();
      }
      if (!flag) {
        cout << ans;
        break;
      }
    }
  }
}
