#include <bits/stdc++.h>
using namespace std;
void Fast_IO() {
  ios::sync_with_stdio(0);
  cin.tie(0);
}
long long n, m;
vector<pair<pair<long long, long long>, long long> > edge;
bool can(long long d) {
  vector<pair<long long, long long> > adj;
  for (auto x : edge)
    if (x.second <= d) adj.push_back(x.first);
  long long out[n], in[n];
  for (long long i = (long long)0; i <= (long long)n - 1; i++)
    out[i] = in[i] = 0;
  for (auto x : adj) out[x.first]++, in[x.second]++;
  for (long long i = (long long)0; i <= (long long)n - 1; i++)
    if (out[i] == 0 || in[i] == 0) return false;
  return true;
}
int main() {
  Fast_IO();
  cin >> n >> m;
  for (long long i = (long long)0; i <= (long long)m - 1; i++) {
    long long u, v, d;
    cin >> u >> v >> d;
    u--;
    v--;
    edge.push_back(make_pair(make_pair(u, v), d));
  }
  long long lo = 1, hi = 1e9;
  if (m < n || !can(hi)) {
    cout << -1;
    return 0;
  }
  while (lo < hi) {
    long long mid = (lo + hi) / 2;
    if (can(mid))
      hi = mid;
    else
      lo = mid + 1;
  }
  cout << lo;
  return 0;
}
