#include <bits/stdc++.h>
const long long maxn = 1e4 + 7;
using namespace std;
struct _IO {
  _IO() {
    ios::sync_with_stdio(0);
    cin.tie(0);
  }
} _io;
inline int read() {
  int s = 0, w = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') w = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
  return s * w;
}
const int N = 1e4 + 10, M = 1e5 + 10;
struct Edge {
  int u, v, t;
} edge[M];
int head[N * 3], cent;
int n, m;
int maxflow;
int dep[N * 3], ans[N * 3], vir[N * 3];
struct Node {
  int ui, vi;
  int ti;
  int next;
} node[M * 4];
void add(int u, int v, int t) {
  node[cent].vi = v;
  node[cent].ti = t;
  node[cent].next = head[u];
  head[u] = cent++;
}
bool bfs() {
  for (int i = 0; i <= 2 * n + 1; i++) {
    dep[i] = 0x3f3f3f3f;
    ans[i] = 0;
    vir[i] = head[i];
  }
  queue<int> q;
  q.push(0);
  dep[0] = 0;
  while (!q.empty()) {
    int now = q.front();
    q.pop();
    ans[now] = 0;
    for (int i = head[now]; ~i; i = node[i].next) {
      int to = node[i].vi;
      if (dep[to] > dep[now] + 1 && node[i].ti) {
        dep[to] = dep[now] + 1;
        if (ans[to] == 0) {
          ans[to] = 1;
          q.push(to);
        }
      }
    }
  }
  if (dep[2 * n + 1] != 0x3f3f3f3f) return 1;
  return 0;
}
int dfs(int u, int flow) {
  int rlow = 0;
  if (u == 2 * n + 1) {
    maxflow += flow;
    return flow;
  }
  int used = 0;
  for (int i = vir[u]; ~i; i = node[i].next) {
    vir[u] = i;
    int d = node[i].vi;
    if (node[i].ti && dep[d] == dep[u] + 1) {
      if (rlow = dfs(d, min(flow - used, node[i].ti))) {
        used += rlow;
        node[i].ti -= rlow;
        node[i ^ 1].ti += rlow;
        if (used == flow) break;
      }
    }
  }
  return used;
}
int Dinic() {
  while (bfs()) {
    dfs(0, 0x3f3f3f3f);
  }
  return maxflow;
}
int check(int f) {
  memset(head, -1, sizeof(head));
  cent = 0;
  for (int i = 1; i <= n; i++) {
    add(0, i, 1);
    add(i, 0, 0);
    add(n + i, 2 * n + 1, 1);
    add(2 * n + 1, n + i, 0);
  }
  for (int i = 1; i <= m; i++) {
    if (edge[i].t <= f) {
      add(edge[i].u, edge[i].v + n, 1);
      add(edge[i].v + n, edge[i].u, 0);
    }
  }
  maxflow = 0;
  Dinic();
  if (maxflow < n)
    return 0;
  else
    return 1;
}
int main() {
  cin >> n >> m;
  int minn = 0x3f3f3f3f, maxn = 0;
  for (int i = 1; i <= m; i++) {
    cin >> edge[i].u >> edge[i].v >> edge[i].t;
    minn = min(minn, edge[i].t);
    maxn = max(maxn, edge[i].t);
  }
  int l = minn, r = maxn;
  int res = -1;
  while (l <= r) {
    int mid = (l + r) / 2;
    if (check(mid)) {
      res = mid;
      r = mid - 1;
    } else
      l = mid + 1;
  }
  cout << res << '\n';
}
