#include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
const long double pi = acos(-1);
const long double eps = 1e-7;
const int INF = 0x3f3f3f3f;
const long long INFLL = 0x3f3f3f3f3f3f3f3f;
const int maxn = 20010;
const int maxm = 1000010;
long long n, m;
struct maxflow {
  long long d[maxn] = {0};
  long long now[maxn] = {0};
  long long st, ed;
  long long head[maxn];
  long long cnt;
  struct Edge {
    long long v, nxt;
    long long w;
  } e[maxm];
  void add(long long u, long long v, long long w) {
    e[++cnt].v = v;
    e[cnt].nxt = head[u];
    head[u] = cnt;
    e[cnt].w = w;
    add_dinic(v, u);
  }
  maxflow(long long s, long long t) : st(s), ed(t) { init(); }
  inline void init() {
    memset(head, -1, sizeof(head));
    cnt = 1;
  }
  inline void clear() {
    memset(now, 0, sizeof(now));
    init();
  }
  void add_dinic(long long u, long long v) {
    e[++cnt].v = v;
    e[cnt].w = 0;
    e[cnt].nxt = head[u];
    head[u] = cnt;
  }
  long long dfs_dinic(long long x, long long flow) {
    if (x == ed) return flow;
    long long res = 0;
    for (long long i = now[x]; i != -1; i = e[i].nxt) {
      long long v = e[i].v;
      now[x] = i;
      if (d[v] + 1 == d[x] && e[i].w > 0) {
        long long k = dfs_dinic(v, min(e[i].w, flow));
        res += k;
        flow -= k;
        e[i].w -= k;
        e[i ^ 1].w += k;
        if (!flow) break;
      }
    }
    return res;
  }
  bool bfs_dinic() {
    memset(d, 0, sizeof(d));
    queue<long long> q;
    q.push(ed);
    d[ed] = 1;
    while (!q.empty()) {
      long long u = q.front();
      q.pop();
      for (long long i = head[u]; i != -1; i = e[i].nxt) {
        long long v = e[i].v;
        if (!d[v] && e[i ^ 1].w > 0) {
          q.push(v);
          d[v] = d[u] + 1;
        }
      }
    }
    return d[st] > 0;
  }
  long long dinic() {
    long long flow = 0;
    while (bfs_dinic()) {
      for (long long i = 0; i <= ed; i++) now[i] = head[i];
      flow += dfs_dinic(st, 0x3f3f3f3f);
    }
    return flow;
  }
} mf(maxn - 2, maxn - 1);
vector<tuple<int, int, int>> e;
bool check(long long x) {
  mf.clear();
  for (auto it : e) {
    if (get<0>(it) > x) break;
    mf.add(get<1>(it), get<2>(it) + n, 1);
  }
  for (int i = (1); i <= (n); i++) {
    mf.add(mf.st, i, 1);
    mf.add(i + n, mf.ed, 1);
  }
  return mf.dinic() == n;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  long long l = 1;
  long long r = 1e9;
  for (int i = (1); i <= (m); i++) {
    int u, v, d;
    cin >> u >> v >> d;
    e.emplace_back(d, u, v);
  }
  sort(e.begin(), e.end());
  while (l < r) {
    long long mid = (l + r) >> 1;
    if (!check(mid))
      l = mid + 1;
    else
      r = mid;
  }
  if (!check(l))
    cout << -1;
  else
    cout << l;
}
