#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct HopcroftKarp {
  struct Node {
    long long id;
    long long level;
    Node* pair;
    std::vector<Node*> adj;
    bool used;
    Node(const long long& ii) : id(ii), level(-1), pair(nullptr), used(false) {}
  };
  long long n;
  std::vector<Node*> graph;
  HopcroftKarp(const long long& nn) {
    n = nn;
    graph.resize(n);
    for (long long i = 0; i < n; ++i) graph[i] = new Node(i);
  }
  ~HopcroftKarp(void) {
    for (Node* e : graph) delete e;
  }
  void add_edge(const long long& a, const long long& b) {
    if (!graph[a] || !graph[b]) return;
    graph[a]->adj.push_back(graph[b]);
    graph[b]->adj.push_back(graph[a]);
  }
  long long match(void) {
    for (long long match = 0;;) {
      std::queue<Node*> order;
      for (auto& node : graph) {
        node->level = -1;
        if (node->pair == nullptr) {
          node->level = 0;
          order.push(node);
        }
      }
      while (!order.empty()) {
        Node* curr = order.front();
        order.pop();
        for (auto& neigh : curr->adj) {
          Node* w = neigh->pair;
          if (w != nullptr && w->level < 0) {
            w->level = curr->level + 1;
            order.push(w);
          }
        }
      }
      for (auto& node : graph) node->used = false;
      long long d = 0;
      for (auto& node : graph) d += node->pair == nullptr && dfs(node);
      match += d;
      if (d == 0) return match;
    }
  }
  bool dfs(Node* curr) {
    curr->used = true;
    for (auto& neigh : curr->adj) {
      Node* w = graph[neigh->id]->pair;
      if (w == nullptr || !w->used && curr->level < w->level && dfs(w)) {
        curr->pair = neigh;
        neigh->pair = curr;
        return true;
      }
    }
    return false;
  }
};
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  int n, m;
  cin >> n >> m;
  vector<array<int, 3> > e(m);
  for (int i = 0; i < m; i++) {
    cin >> e[i][1] >> e[i][2] >> e[i][0];
    e[i][1]--;
    e[i][2]--;
  }
  sort(e.begin(), e.end());
  int lo = 0, hi = e.back()[0] + 1;
  while (lo < hi) {
    int mid = (lo + hi) / 2;
    HopcroftKarp g(2 * n);
    for (int i = 0; i < m; i++) {
      if (e[i][0] > mid) break;
      g.add_edge(e[i][1], e[i][2] + n);
    }
    if (g.match() == n) {
      hi = mid;
    } else {
      lo = mid + 1;
    }
  }
  if (hi > e.back()[0]) {
    cout << "-1\n";
  } else {
    cout << hi << "\n";
  }
  return 0;
}
