#include <bits/stdc++.h>
using namespace std;
const int MAXN = 20202;
const int MAXM = 101010;
int N, M, u[MAXM], v[MAXM], d[MAXM];
struct FlowEdge {
  int v, u;
  long long cap, flow = 0;
  FlowEdge(int v, int u, long long cap) : v(v), u(u), cap(cap) {}
};
struct Dinic {
  const long long flow_inf = 1e18;
  vector<FlowEdge> edges;
  vector<vector<int>> adj;
  int n, m = 0;
  int s, t;
  vector<int> level, ptr;
  queue<int> q;
  Dinic(int n, int s, int t) : n(n), s(s), t(t) {
    adj.resize(n);
    level.resize(n);
    ptr.resize(n);
  }
  void add_edge(int v, int u, long long cap) {
    edges.emplace_back(v, u, cap);
    edges.emplace_back(u, v, 0);
    adj[v].push_back(m);
    adj[u].push_back(m + 1);
    m += 2;
  }
  bool bfs() {
    while (!q.empty()) {
      int v = q.front();
      q.pop();
      for (int id : adj[v]) {
        if (edges[id].cap - edges[id].flow < 1) continue;
        if (level[edges[id].u] != -1) continue;
        level[edges[id].u] = level[v] + 1;
        q.push(edges[id].u);
      }
    }
    return level[t] != -1;
  }
  long long dfs(int v, long long pushed) {
    if (pushed == 0) return 0;
    if (v == t) return pushed;
    for (int& cid = ptr[v]; cid < (int)adj[v].size(); cid++) {
      int id = adj[v][cid];
      int u = edges[id].u;
      if (level[v] + 1 != level[u] || edges[id].cap - edges[id].flow < 1)
        continue;
      long long tr = dfs(u, min(pushed, edges[id].cap - edges[id].flow));
      if (tr == 0) continue;
      edges[id].flow += tr;
      edges[id ^ 1].flow -= tr;
      return tr;
    }
    return 0;
  }
  long long flow() {
    long long f = 0;
    while (true) {
      fill(level.begin(), level.end(), -1);
      level[s] = 0;
      q.push(s);
      if (!bfs()) break;
      fill(ptr.begin(), ptr.end(), 0);
      while (long long pushed = dfs(s, flow_inf)) {
        f += pushed;
      }
    }
    return f;
  }
};
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> N >> M;
  for (int i = 0; i < M; i++) {
    cin >> u[i] >> v[i] >> d[i];
  }
  int lo = 0, hi = 1e9 + 1;
  while (lo <= hi) {
    int mid = (lo + hi) / 2;
    Dinic dinic = Dinic(2 * N + 2, 0, 2 * N + 1);
    for (int i = 1; i <= N; i++) dinic.add_edge(0, i, 1);
    for (int i = N + 1; i <= 2 * N; i++) dinic.add_edge(i, 2 * N + 1, 1);
    for (int i = 0; i < M; i++) {
      if (d[i] <= mid) {
        dinic.add_edge(u[i], v[i] + N, 1);
      }
    }
    if (dinic.flow() == N)
      hi = mid - 1;
    else
      lo = mid + 1;
  }
  if (hi == 1e9 + 1)
    cout << -1 << '\n';
  else
    cout << hi + 1 << '\n';
}
