#include <bits/stdc++.h>
using namespace std;
struct Dinic {
  static constexpr int INF = 1e9 + 7;
  int n;
  struct Edge {
    int to, cap;
    Edge(int to, int cap) : to(to), cap(cap) {}
  };
  vector<vector<int>> g;
  vector<Edge> e;
  Dinic(int n) : n(n), g(n) {}
  vector<int> cur, h;
  bool bfs(int s, int t) {
    h.assign(n, -1);
    queue<int> que;
    h[s] = 0;
    que.push(s);
    while (!que.empty()) {
      int u = que.front();
      que.pop();
      for (int i : g[u]) {
        int v = e[i].to, c = e[i].cap;
        if (c > 0 && h[v] == -1) {
          h[v] = h[u] + 1;
          que.push(v);
          if (v == t) return true;
        }
      }
    }
    return false;
  }
  int dfs(int u, int t, int f) {
    if (u == t) return f;
    int r = f;
    for (int& i = cur[u]; i < int(g[u].size()); i++) {
      int j = g[u][i];
      int v = e[j].to, c = e[j].cap;
      if (c > 0 && h[v] == h[u] + 1) {
        int a = dfs(v, t, min(r, c));
        e[j].cap -= a;
        e[j ^ 1].cap += a;
        r -= a;
        if (r == 0) return f;
      }
    }
    return f - r;
  }
  void addedge(int u, int v, int c) {
    g[u].push_back(e.size());
    e.emplace_back(v, c);
    g[v].push_back(e.size());
    e.emplace_back(u, 0);
  }
  int flow(int s, int t) {
    int ans = 0;
    while (bfs(s, t)) {
      cur.assign(n, 0);
      ans += dfs(s, t, INF);
    }
    return ans;
  }
};
int main() {
  ios::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  vector<int> u(m), v(m), d(m);
  for (int i = 0; i < m; i++) {
    cin >> u[i] >> v[i] >> d[i];
    --u[i], --v[i];
  }
  int l = 0, r = 1e9 + 1;
  while (l < r) {
    int mid = l + (r - l) / 2;
    Dinic f(2 * n + 2);
    for (int i = 0; i < n; i++) {
      f.addedge(2 * n, i, 1);
      f.addedge(n + i, 2 * n + 1, 1);
    }
    for (int i = 0; i < m; i++) {
      if (d[i] <= mid) f.addedge(u[i], n + v[i], 1);
    }
    if (f.flow(2 * n, 2 * n + 1) == n)
      r = mid;
    else
      l = mid + 1;
  }
  if (r == 1e9 + 1) r = -1;
  cout << r << endl;
  return 0;
}
