#include <bits/stdc++.h>
using namespace std;
const long double PI = 3.141592653589793;
const long double DEL = 1e-10;
const int mod = 1000000007;
inline void read(long long &x) {
  long long c = getchar();
  x = 0;
  long long neg = 0;
  for (; ((c < 48 || c > 57) && c != '-'); c = getchar())
    ;
  if (c == '-') {
    neg = 1;
    c = getchar();
  }
  for (; c > 47 && c < 58; c = getchar()) {
    x = (x << 1) + (x << 3) + c - 48;
  }
  if (neg) {
    x = -x;
  }
}
long long fpow(long long x, long long n) {
  long long res = 1;
  while (n) {
    if (n & 1) {
      res = res * x % mod;
    }
    x = x * x % mod;
    n >>= 1;
  }
  return res;
}
long long gcd(long long a, long long b) {
  if (b == 0) {
    return a;
  }
  return gcd(b, a % b);
}
void sieve(long long n) {
  bool prime[1000006];
  memset(prime, true, sizeof(prime));
  long long rootn = (long long)sqrt(n);
  for (long long p = 2; p <= rootn; p++) {
    if (prime[p] == true) {
      for (long long i = p * p; i <= n; i += p) {
        prime[i] = false;
      }
    }
  }
  prime[1] = 0;
}
const long long N = 100050;
long long cnt, sum, mid, mx, mn, ans, a[N], b[N];
long long n, m, d, i, j, k, l, p, q, r, t, w, x, y, z;
bool f, f1, f2;
string s;
vector<pair<long long, pair<long long, long long>>> e;
bool check(long long d) {
  vector<bool> air(n + 2), fac(n + 2);
  for (auto j : e) {
    if (j.first > d) break;
    air[j.second.first] = 1;
    fac[j.second.second] = 1;
  }
  for (long long i = 1; i <= n; i++) {
    if (!air[i] || !fac[i]) {
      return false;
    }
  }
  return true;
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (i = 1; i <= m; i++) {
    cin >> x >> y >> z;
    e.push_back({z, {x, y}});
  }
  sort(e.begin(), e.end());
  l = 1;
  r = 1e9 + 2;
  while (l < r) {
    mid = (l + r) / 2;
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  if (r > 1e9) {
    cout << -1;
  } else {
    cout << r;
  }
}
