#include <bits/stdc++.h>
using namespace std;
const int N = 20005, M = 100005;
const int INF = 0x3f3f3f3f;
int n, m, s, t, dis[N], cur[N], h[N], num, ans;
struct Edge {
  int x, t, w;
} e[2 * (M + 2 * N)];
struct node {
  int x, y, z;
} p[M];
inline int read() {
  int f = 1, x = 0;
  char ch = getchar();
  while (ch > '9' || ch < '0') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return f * x;
}
inline void add(int s, int t, int w) {
  e[++num].x = h[s], e[num].t = t, e[num].w = w, h[s] = num;
}
inline bool bfs() {
  queue<int> q;
  memset(dis, 0, sizeof(dis));
  memcpy(cur, h, sizeof(h));
  dis[s] = 1;
  q.push(s);
  while (!q.empty()) {
    int now = q.front();
    q.pop();
    for (int i = h[now]; i; i = e[i].x)
      if (e[i].w && !dis[e[i].t]) {
        dis[e[i].t] = dis[now] + 1;
        q.push(e[i].t);
      }
  }
  return dis[t] != 0;
}
inline int dfs(int now, int lim) {
  if (now == t) return lim;
  int k, res = 0;
  for (int& i = cur[now]; i; i = e[i].x)
    if (e[i].w && dis[e[i].t] == dis[now] + 1) {
      k = dfs(e[i].t, min(lim, e[i].w));
      e[i].w -= k, e[i ^ 1].w += k, res += k, lim -= k;
      if (lim == 0) break;
    }
  return res;
}
inline bool check(int x) {
  num = 1, ans = 0, memset(h, 0, sizeof(h));
  for (int i = (1), iend = (n); i <= iend; i++) add(s, i, 1), add(i, s, 0);
  for (int i = (1), iend = (n); i <= iend; i++)
    add(i + n, t, 1), add(t, i + n, 0);
  for (int i = (1), iend = (m); i <= iend; i++)
    if (p[i].z <= x) {
      add(p[i].x, p[i].y + n, 1);
      add(p[i].y + n, p[i].x, 0);
    }
  while (bfs()) ans += dfs(s, INF);
  return ans == n;
}
int main() {
  n = read(), m = read();
  s = 0, t = 2 * n + 1;
  for (int i = (1), iend = (m); i <= iend; i++)
    p[i].x = read(), p[i].y = read(), p[i].z = read();
  if (!check(1e9)) {
    printf("-1");
    return 0;
  }
  int l = 1, r = 1e9, ans;
  while (l <= r) {
    int mid = (l + r) >> 1;
    if (check(mid))
      ans = mid, r = mid - 1;
    else
      l = mid + 1;
  }
  printf("%d", ans);
  return 0;
}
