#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 100;
namespace Din {
const int MX = 1e6 + 100;
const int INF = 1e9;
struct Edge {
  int to, w, nxt;
  Edge(int _to = 0, int _w = 0, int _nxt = 0) : to(_to), w(_w), nxt(_nxt) {}
} e[MX << 1];
int head[MX], d[MX], cur[MX], tot;
int s, t, N;
struct Node {
  int x, y, d;
  Node(int _x = 0, int _y = 0, int _d = 0) : x(_x), y(_y), d(_d) {}
} no[maxn];
void init(int n, int ss, int tt) {
  s = ss;
  t = tt;
  N = n;
  tot = 1;
  for (int i = 0; i <= n + 5; i++) head[i] = 0;
}
void addedge(int x, int y, int z) {
  e[++tot] = Edge(y, z, head[x]);
  head[x] = tot;
  swap(x, y);
  e[++tot] = Edge(y, 0, head[x]);
  head[x] = tot;
}
bool bfs() {
  for (int i = 0; i <= N + 10; i++) d[i] = 0;
  queue<int> q;
  while (q.size()) q.pop();
  d[s] = 1;
  q.push(s);
  while (q.size()) {
    int x = q.front();
    q.pop();
    for (int i = head[x]; i; i = e[i].nxt) {
      int y = e[i].to, w = e[i].w;
      if (d[y] || !w) continue;
      d[y] = d[x] + 1;
      q.push(y);
      if (y == t) return true;
    }
  }
  return false;
}
int dfs(int x, int flow) {
  if (x == t) return flow;
  int ret = 0;
  for (int &i = cur[x]; i; i = e[i].nxt) {
    int y = e[i].to, w = e[i].w;
    if (d[y] != d[x] + 1 || !w) continue;
    int now = dfs(y, min(flow - ret, w));
    if (now > 0) {
      e[i].w -= now;
      e[i ^ 1].w += now;
      ret += now;
      if (ret == flow) break;
    }
  }
  return ret;
}
int maxflow() {
  int Maxflow = 0;
  while (bfs()) {
    for (int i = 0; i <= N + 10; i++) cur[i] = head[i];
    Maxflow += dfs(s, INF);
  }
  return Maxflow;
}
bool judge(int n, int m, int cost) {
  int ss = 2 * n + 1, tt = 2 * n + 2;
  init(2 * n + 2, ss, tt);
  for (int i = 1; i <= n; i++) addedge(s, i, 1);
  for (int i = n + 1; i <= 2 * n; i++) addedge(i, t, 1);
  for (int i = 1; i <= m; i++) {
    int x = no[i].x, y = no[i].y, d = no[i].d;
    if (d > cost) continue;
    addedge(x, y + n, 1);
  }
  if (maxflow() == n) return true;
  return false;
}
void solve() {
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int x, y, d;
    scanf("%d %d %d", &x, &y, &d);
    no[i] = Node(x, y, d);
  }
  if (judge(n, m, INF)) {
    int low = 1, high = INF;
    while (low < high) {
      int mid = (low + high) >> 1;
      if (judge(n, m, mid))
        high = mid;
      else
        low = mid + 1;
    }
    printf("%d\n", low);
  } else {
    printf("-1\n");
  }
}
};  // namespace Din
int main() {
  Din::solve();
  return 0;
}
