#include <bits/stdc++.h>
using namespace std;
static const int MAX = 100000;
static const long long INF = 1e15;
static const int white = 0;
static const int gray = 1;
static const int black = 2;
int n, m;
vector<pair<int, int>> adj[MAX];
void dijkstra() {
  priority_queue<pair<long long, long long>> pq;
  int color[MAX];
  long long d[MAX];
  for (int i = 0; i < n; i++) {
    d[i] = INF;
    color[i] = white;
  }
  d[0] = 0;
  pq.push(make_pair(0, 0));
  color[0] = gray;
  while (!pq.empty()) {
    pair<int, int> f = pq.top();
    pq.pop();
    int u = f.second;
    color[u] = black;
    if (d[u] < f.first * (-1)) continue;
    for (int j = 0; j < adj[u].size(); j++) {
      int k = adj[u][j].first;
      if (u < k) {
        for (int v = k; v > u; v--) {
          if (color[v] == black) continue;
          if (d[v] > d[u] + adj[u][j].second) {
            d[v] = d[u] + adj[u][j].second;
            pq.push(make_pair(d[v] * (-1), v));
            color[v] = gray;
          }
        }
      } else {
        for (int v = k; v < u; v++) {
          if (color[v] == black) continue;
          if (d[v] > d[u] + adj[u][j].second) {
            d[v] = d[u] + adj[u][j].second;
            pq.push(make_pair(d[v] * (-1), v));
            color[v] = gray;
          }
        }
      }
    }
  }
  cout << (d[n - 1] == INF ? -1 : d[n - 1]) << endl;
}
int main() {
  int l, r, c;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    cin >> l >> r >> c;
    l--;
    r--;
    adj[l].push_back(make_pair(r, c));
    adj[r].push_back(make_pair(l, c));
  }
  dijkstra();
  return 0;
}
