#include <bits/stdc++.h>
using namespace std;
const long long maxn = 3e5 + 50;
const long long inf = 0x3f3f3f3f3f3f3f3f;
long long n, m, cnt;
long long head[maxn];
long long level[maxn];
long long cur[maxn];
struct Edge {
  long long to;
  long long val;
  long long next;
} edge[maxn];
void add(long long u, long long v, long long val) {
  edge[cnt].to = v;
  edge[cnt].val = val;
  edge[cnt].next = head[u];
  head[u] = cnt++;
  edge[cnt].to = u;
  edge[cnt].val = 0;
  edge[cnt].next = head[v];
  head[v] = cnt++;
}
bool find_level(long long s, long long t) {
  queue<long long> q;
  memset(level, 0, sizeof(level));
  for (long long i = 1; i <= n; i++) {
    cur[i] = head[i];
  }
  long long u = s;
  level[u] = 1;
  q.push(u);
  while (!q.empty()) {
    u = q.front();
    q.pop();
    for (long long i = head[u]; ~i; i = edge[i].next) {
      long long v = edge[i].to;
      long long val = edge[i].val;
      if (!level[v] && val) {
        level[v] = level[u] + 1;
        q.push(v);
      }
    }
    if (level[t]) {
      return true;
    }
  }
  return false;
}
long long updata(long long u, long long u_val, long long t) {
  if (u == t) {
    return u_val;
  }
  long long used = 0;
  for (long long &i = cur[u]; ~i; i = edge[i].next) {
    long long v = edge[i].to;
    long long val = edge[i].val;
    if (level[v] == level[u] + 1 && val) {
      long long tmp = updata(v, min(u_val - used, val), t);
      edge[i].val -= tmp;
      edge[i ^ 1].val += tmp;
      used += tmp;
      if (used == u_val) return used;
    }
  }
  if (used == 0) level[u] = -1;
  return used;
}
long long Dinic(long long s, long long t) {
  long long ans = 0;
  while (find_level(s, t)) {
    ans += updata(s, inf, t);
  }
  return ans;
}
void init() {
  cnt = 0;
  memset(head, -1, sizeof(head));
}
struct node {
  long long from, to, val;
} a[maxn];
long long nn;
bool check(long long mid) {
  init();
  long long s = 1, t = 2 * nn + 2;
  n = t;
  for (long long i = 1; i <= nn; i++) {
    add(1, i + 1, 1);
    add(i + 1 + nn, t, 1);
  }
  for (long long i = 1; i <= m; i++) {
    if (a[i].val <= mid) add(a[i].from, a[i].to, a[i].val);
  }
  if (Dinic(s, t) == nn)
    return true;
  else
    return false;
}
signed main() {
  scanf("%lld %lld", &n, &m);
  nn = n;
  long long r = 0, l = 0;
  long long maxx = 0;
  for (long long i = 1; i <= m; i++) {
    scanf("%lld %lld %lld", &a[i].from, &a[i].to, &a[i].val);
    a[i].from += 1;
    a[i].to += n + 1;
    r = max(r, a[i].val);
  }
  r++;
  maxx = r;
  while (l < r) {
    long long mid = (l + r) / 2;
    if (check(mid)) {
      r = mid;
    } else
      l = mid + 1;
  }
  if (l == maxx)
    printf("-1\n");
  else
    printf("%lld\n", l);
  return 0;
}
