#include <bits/stdc++.h>
const double pi = acos(-1.0);
const int maxn = (1e5 + 10);
const int inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
using namespace std;
struct node {
  int x, y, val;
} a[maxn];
int p[maxn];
bool cmp(node a, node b) { return a.val < b.val; }
vector<int> v[maxn];
int n, m, maxx = -1;
int nx, ny;
int mx[100010], my[100010];
int dx[100010], dy[100010];
bool pd[100010];
bool find(int now) {
  for (int i = 0; i < v[now].size(); i++) {
    int id = v[now][i];
    if (!pd[id] && dy[id] == dx[now] + 1) {
      pd[id] = true;
      if (my[id] == 0 || find(my[id])) {
        mx[now] = id;
        my[id] = now;
        return true;
      }
    }
  }
  return false;
}
int hk() {
  memset(mx, 0, sizeof(mx));
  memset(my, 0, sizeof(my));
  int ans = 0;
  while (true) {
    bool swt = false;
    queue<int> q;
    memset(dx, 0, sizeof(dx));
    memset(dy, 0, sizeof(dy));
    for (int i = 1; i <= nx; i++)
      if (mx[i] == 0) q.push(i);
    while (!q.empty()) {
      int now = q.front();
      q.pop();
      for (int i = 0; i < v[now].size(); i++) {
        int id = v[now][i];
        if (dy[id] == 0) {
          dy[id] = dx[now] + 1;
          if (my[id]) {
            dx[my[id]] = dy[id] + 1;
            q.push(my[id]);
          } else {
            swt = true;
          }
        }
      }
    }
    if (swt == false) break;
    memset(pd, false, sizeof(pd));
    for (int i = 1; i <= nx; i++)
      if (!mx[i] && find(i)) ans += 1;
  }
  return ans;
}
bool check(int val) {
  for (int i = 1; i <= n; i++) v[i].clear();
  int pos = upper_bound(p + 1, p + 1 + m, val) - p;
  for (int i = 1; i <= pos - 1; i++) {
    int x = a[i].x, y = a[i].y;
    v[x].push_back(y);
  }
  nx = n;
  ny = n;
  int now = hk();
  if (now == n)
    return true;
  else
    return false;
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    cin >> a[i].x >> a[i].y >> a[i].val;
    p[i] = a[i].val;
    maxx = max(maxx, a[i].val);
  }
  sort(a + 1, a + 1 + m, cmp);
  sort(p + 1, p + 1 + m);
  int l = 1, r = maxx, ans = -1;
  while (l <= r) {
    int mid = (l + r) / 2;
    if (check(mid)) {
      r = mid - 1;
      ans = mid;
    } else
      l = mid + 1;
  }
  cout << ans;
  return 0;
}
