#include <bits/stdc++.h>
using namespace std;
int main() {
  int N, M;
  cin >> N >> M;
  vector<vector<pair<int, int>>> G(N + 1);
  for (int x = 0; x < (N); x++) {
    G[x + 1].push_back(make_pair(x, 0));
  }
  for (int x = 0; x < (M); x++) {
    int a, b, c;
    cin >> a >> b >> c;
    G[a].push_back(make_pair(b, c));
    G[b].push_back(make_pair(a, c));
  }
  queue<pair<int, int>> Q;
  Q.push(make_pair(0, 1));
  bool flags[110000] = {
      false,
  };
  long long cost[110000];
  for (int x = 0; x < (N); x++) {
    cost[x + 1] = LLONG_MAX / 2;
  }
  cost[1] = 0;
  while (Q.size()) {
    auto q = Q.front();
    Q.pop();
    if (flags[q.second]) {
      continue;
    }
    flags[q.second] = true;
    for (int x = 0; x < (G[q.second].size()); x++) {
      if (cost[G[q.second][x].first] > cost[q.second] + G[q.second][x].second) {
        cost[G[q.second][x].first] = cost[q.second] + G[q.second][x].second;
        Q.push(make_pair(-cost[G[q.second][x].first], G[q.second][x].first));
      }
    }
  }
  if (cost[N] == LLONG_MAX / 2) {
    cout << -1 << endl;
  } else {
    cout << cost[N] << endl;
  }
  return 0;
}
