#include <bits/stdc++.h>
const int MAXN = 10005;
const int MAXM = 100005;
std::set<int> airports;
std::set<int> factorys;
struct ROAD {
  int u;
  int v;
  int d;
};
ROAD road[MAXM];
int main(int argc, char* argv[]) {
  int t;
  int n, m, k;
  {
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; i++) {
      scanf("%d %d %d", &road[i].u, &road[i].v, &road[i].d);
    }
    int res = -1;
    int low = 1;
    int high = 1000000000;
    while (low <= high) {
      int mid = (low + high) / 2;
      airports.clear();
      factorys.clear();
      for (int i = 1; i <= m; i++) {
        if (road[i].d <= mid) {
          airports.insert(road[i].u);
          factorys.insert(road[i].v);
        }
      }
      if (airports.size() == n && factorys.size() == n) {
        if (res == -1 || mid < res) {
          res = mid;
        }
        high = mid - 1;
      } else {
        low = mid + 1;
      }
    }
    printf("%d\n", res);
  }
  return 0;
}
