#include <bits/stdc++.h>
using namespace std;
const int N = 200010, M = 2e5 + 4e4 + 100, Q = 1e5 + 10, inf = 1e9;
int d[N], nxt[M], to[M], flow[M], tot;
inline void ins(int a, int b, int c) {
  to[++tot] = b, nxt[tot] = d[a], d[a] = tot, flow[tot] = c;
}
inline void add(int a, int b, int c) { ins(a, b, c), ins(b, a, 0); }
int dep[N], cur[N], S, T;
queue<int> q;
inline bool spfa() {
  for (int i = S; i <= T; ++i) dep[i] = 0, cur[i] = d[i];
  q.push(S), dep[S] = 1;
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    for (int i = d[x]; ~i; i = nxt[i]) {
      int u = to[i];
      if (!dep[u] && flow[i]) {
        dep[u] = dep[x] + 1;
        q.push(u);
      }
    }
  }
  return dep[T] != 0;
}
int Maxflow;
inline int dfs(int now, int lim) {
  if (now == T || !lim) {
    Maxflow += lim;
    return lim;
  }
  int fl = 0, f;
  for (int i = cur[now]; ~i; i = nxt[i]) {
    int u = to[i];
    cur[now] = i;
    if (dep[u] == dep[now] + 1 && (f = dfs(u, min(lim, flow[i])))) {
      flow[i] -= f, flow[i ^ 1] += f;
      fl += f, lim -= f;
      if (!lim) return fl;
    }
  }
  return fl;
}
inline int Dinic() {
  Maxflow = 0;
  while (spfa())
    while (dfs(S, inf))
      ;
  return Maxflow;
}
int n, m;
struct edge {
  int u, v, d;
  inline bool operator<(const edge& other) const { return d < other.d; }
} a[Q];
inline bool ck(int x) {
  for (int i = S; i <= T; ++i) d[i] = -1;
  tot = -1;
  for (int i = 1; i <= n; ++i) add(S, i, 1), add(i + n, T, 1);
  for (int i = 1; i <= m; ++i) {
    if (a[i].d > x) break;
    add(a[i].u, a[i].v + n, 1);
  }
  return Dinic() == n;
}
int main() {
  int L, R;
  L = 1e9, R = 0;
  scanf("%d%d", &n, &m);
  S = 0, T = 2 * n + 1;
  for (int i = 1; i <= m; ++i)
    scanf("%d%d%d", &a[i].u, &a[i].v, &a[i].d), R = max(R, a[i].d),
                                                L = min(L, a[i].d);
  sort(a + 1, a + 1 + m);
  int mid, ans = 1e9 + 1;
  while (L <= R) {
    mid = L + R >> 1;
    if (ck(mid))
      ans = mid, R = mid - 1;
    else
      L = mid + 1;
  }
  if (ans > inf)
    printf("-1\n");
  else
    printf("%d\n", ans);
  return 0;
}
