#include <bits/stdc++.h>
using namespace std;
const int MAXV = 20010;
long long INF = 1 << 30;
struct dinic {
  struct edge {
    int to, rev;
    long long cap, flow;
  };
  int s, t;
  long long lim = 1;
  vector<edge> adj[MAXV];
  vector<int> level;
  vector<int> cur_arc;
  void init(int n) {
    s = 0;
    t = n + 1;
    level.clear();
    cur_arc.clear();
    for (int i = 0; i <= n + 1; i++) {
      adj[i].clear();
      level.push_back(-1);
      cur_arc.push_back(0);
    }
  }
  void add_edge(int u, int v, long long cap) {
    if (u == v) return;
    adj[u].push_back((edge){v, (int)adj[v].size(), cap, 0});
    adj[v].push_back((edge){u, (int)adj[u].size() - 1, 0, 0});
  };
  bool bfs() {
    queue<int> q;
    q.push(s);
    fill(level.begin(), level.end(), -1);
    fill(cur_arc.begin(), cur_arc.end(), 0);
    level[s] = 0;
    while (!q.empty() && level[t] == -1) {
      int cur = q.front();
      q.pop();
      for (auto e : adj[cur]) {
        if (level[e.to] == -1 && e.flow + lim <= e.cap) {
          level[e.to] = level[cur] + 1;
          q.push(e.to);
        }
      }
    }
    return level[t] != -1;
  };
  long long dfs(int v, long long flow) {
    if (v == t) return flow;
    long long rem_flow = flow;
    for (; cur_arc[v] < adj[v].size(); cur_arc[v]++) {
      edge &e = adj[v][cur_arc[v]];
      if (level[e.to] == level[v] + 1 && e.flow + lim <= e.cap) {
        long long pushed = dfs(e.to, min(rem_flow, e.cap - e.flow));
        e.flow += pushed;
        adj[e.to][e.rev].flow -= pushed;
        rem_flow -= pushed;
      }
      if (rem_flow < lim) break;
    }
    return flow - rem_flow;
  };
  long long run() {
    long long flow = 0;
    for (lim = INF; lim > 0; lim >>= 1) {
      while (bfs()) {
        long long pushed = dfs(s, INF);
        flow += pushed;
      }
    }
    return flow;
  };
};
struct day_edges {
  int u, v, d;
};
int main() {
  int n, m;
  cin >> n >> m;
  vector<day_edges> es;
  for (int i = 0; i < m; i++) {
    int u, v, d;
    cin >> u >> v >> d;
    es.push_back((day_edges){u, v, d});
  }
  int L = 0, R = (int)(1e9 + 2), ans;
  while (L + 1 < R) {
    ans = (L + R) / 2;
    dinic G;
    G.init(2 * n);
    for (int i = 1; i <= n; i++) {
      G.add_edge(G.s, i, 1);
      G.add_edge(i + n, G.t, 1);
    }
    for (auto e : es) {
      if (e.d <= ans) {
        G.add_edge(e.u, e.v + n, 1);
      }
    }
    int flow = G.run();
    if (flow < n) {
      L = ans;
    } else {
      R = ans;
    }
  }
  if (R > 1e9)
    cout << -1 << endl;
  else
    cout << R << endl;
}
