#include <bits/stdc++.h>
using namespace std;
struct Section {
  long long l;
  long long r;
  long long cost;
  bool operator<(const Section &a) const {
    if (this->l == a.l) {
      if (this->cost == a.cost) {
        return this->r < a.r;
      } else {
        return this->cost > a.cost;
      }
    } else {
      return this->l > a.l;
    }
  }
};
std::priority_queue<Section> q;
int n, m;
int d[100010];
void swap(Section &a, Section &b) {
  long long temp;
  temp = a.l;
  a.l = b.l;
  b.l = temp;
  temp = a.r;
  a.r = b.r;
  b.r = temp;
  temp = a.cost;
  a.cost = b.cost;
  b.cost = temp;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    Section newSection;
    scanf("%lld%lld%lld", &(newSection.l), &(newSection.r), &(newSection.cost));
    q.push(newSection);
  }
  Section curSection;
  curSection = q.top();
  q.pop();
  if (curSection.l != 1) {
    printf("-1\n");
    return 0;
  }
  long long totalCost = 0;
  while (!q.empty()) {
    Section nextSection = q.top();
    q.pop();
    if (curSection.r == nextSection.l) {
      totalCost = totalCost + curSection.cost;
      curSection.l = nextSection.l;
      curSection.r = nextSection.r;
      curSection.cost = nextSection.cost;
      continue;
    }
    if (curSection.l == nextSection.l) {
      if (curSection.cost > nextSection.cost) swap(curSection, nextSection);
      if (curSection.r < nextSection.r) {
        nextSection.l = curSection.r;
        q.push(nextSection);
        continue;
      }
    } else {
      if (curSection.r < nextSection.l) {
        printf("-1\n");
        return 0;
      }
      if (curSection.cost <= nextSection.cost) {
        if (curSection.r < nextSection.r) {
          nextSection.l = curSection.r;
          q.push(nextSection);
          continue;
        }
      } else {
        if (curSection.r < nextSection.r) {
          nextSection.l = curSection.r;
          q.push(nextSection);
          continue;
        }
      }
    }
  }
  totalCost = totalCost + curSection.cost;
  printf("%lld\n", totalCost);
  return 0;
}
