#include <bits/stdc++.h>
using namespace std;
const int N = 100100;
long long n, m, deg1[N], deg2[N];
vector<pair<pair<long long, long long>, int> > edges;
bool ok(long long mid) {
  memset(deg1, 0, sizeof deg1);
  memset(deg2, 0, sizeof deg2);
  for (auto x : edges)
    if (x.second <= mid) {
      deg1[x.first.first]++;
      deg2[x.first.second]++;
    }
  for (int i = 1; i <= n; i++)
    if (min(deg1[i], deg2[i]) == 0) return 0;
  return 1;
}
int main() {
  scanf("%lld%lld", &n, &m);
  for (int i = 1; i <= m; i++) {
    long long a, b, c;
    scanf("%lld%lld%lld", &a, &b, &c);
    edges.push_back({{a, b}, c});
  }
  long long low = 1, high = 1e9;
  while (low < high) {
    long long mid = (low + high) / 2;
    if (ok(mid))
      high = mid;
    else
      low = mid + 1;
  }
  if (ok(low))
    printf("%lld\n", low);
  else
    printf("-1\n");
}
