#include <bits/stdc++.h>
using namespace std;
const long long N = 4400000;
const long long M = 21000000;
const long long inf = 0x3f3f3f3f;
long long read() {
  char ch = getchar();
  long long x = 0, f = 1;
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = (x << 1) + (x << 3) + ch - '0';
    ch = getchar();
  }
  return x * f;
}
long long pre[N], to[M], nxt[M], w[M], ls[N], rs[N], pos[N], dis[N], sz, top,
    ra, rb, n, m;
bool vis[N];
void add(long long u, long long v, long long ww = 0) {
  to[++top] = v;
  nxt[top] = pre[u];
  pre[u] = top;
  w[top] = ww;
}
struct data {
  long long a, b;
  data(long long aa = 0, long long bb = 0) : a(aa), b(bb) {}
  bool operator<(data a) const { return b > a.b; }
};
void Build(long long &p, long long L, long long R, bool flag) {
  if (!p) p = ++sz;
  if (L == R) {
    if (flag) pos[L] = sz;
    return;
  }
  long long mid = L + R >> 1;
  Build(ls[p], L, mid, flag);
  Build(rs[p], mid + 1, R, flag);
  if (flag)
    add(ls[p], p), add(rs[p], p);
  else
    add(p, ls[p]), add(p, rs[p]);
}
void Add(long long pa, long long pb, long long L, long long R) {
  if (L == R) {
    add(pb, pa);
    return;
  }
  long long mid = L + R >> 1;
  Add(ls[pa], ls[pb], L, mid);
  Add(rs[pa], rs[pb], mid + 1, R);
}
void Update(long long p, long long L, long long R, long long st, long long ed,
            long long c, bool flag) {
  if (L == st && ed == R) {
    if (flag)
      add(p, c, 0);
    else
      add(c, p, 0);
    return;
  }
  long long mid = L + R >> 1;
  if (st <= mid) Update(ls[p], L, mid, st, min(mid, ed), c, flag);
  if (ed > mid) Update(rs[p], mid + 1, R, max(st, mid + 1), ed, c, flag);
}
void Link(long long a, long long b, long long c, long long d, long long ww) {
  Update(ra, 1, n, a, b, ++sz, ww);
  add(sz, sz + 1, ww);
  Update(rb, 1, n, c, d, ++sz, 0);
}
void Dij() {
  for (long long i = 1; i <= sz; ++i) dis[i] = inf;
  priority_queue<data> q;
  dis[pos[1]] = 0;
  q.push(data(pos[1], 0));
  while (!q.empty()) {
    long long u = q.top().a;
    q.pop();
    if (vis[u]) continue;
    vis[u] = true;
    for (long long i = pre[u]; i; i = nxt[i])
      if (!vis[to[i]] && dis[to[i]] > dis[u] + w[i]) {
        dis[to[i]] = dis[u] + w[i];
        q.push(data(to[i], dis[to[i]]));
      }
  }
}
signed main() {
  scanf("%lld%lld", &n, &m);
  Build(ra, 1, n, 1);
  Build(rb, 1, n, 0);
  Add(ra, rb, 1, n);
  for (long long i = 1; i <= m; ++i) {
    long long a, b;
    long long ww;
    scanf("%lld%lld%lld", &a, &b, &ww);
    Link(a, b, a, b, ww);
  }
  Dij();
  if (dis[pos[n]] > (long long)1e16)
    printf("-1");
  else
    printf("%lld\n", dis[pos[n]]);
  return 0;
}
