#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcountll

#define INF 1e16
#define mod 1000000007

struct UnionFind{
  vector<int> v;
  UnionFind(int n) : v(n, -1) {}
  void init(){ for(int i = 0;i < (int)v.size();i++)v[i]=-1; }
  int find(int x) { return v[x] < 0 ? x : v[x] = find(v[x]); }
  bool unite(int x, int y) {
    x = find(x); y = find(y);
    if (x == y) return false;
    if (-v[x] < -v[y]) swap(x, y);
    v[x] += v[y]; v[y] = x;
    return true;
  }
  bool root(int x) { return v[x] < 0; }
  bool same(int x, int y) { return find(x) == find(y); }
  int size(int x) { return -v[find(x)]; }
};

struct edge{
  ll u,v,cost;
};

ll n,q;
vector<ll> a,b,c;
vector<edge> es;
vector<vector<ll>> bs;

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);

  cin>>n>>q;
  a.resize(q); b.resize(q); c.resize(q);
  bs.resize(2*n);
  rep(i,q){
    cin>>a[i]>>b[i]>>c[i];
    es.push_back((edge){a[i],b[i],c[i]});
    bs[a[i]].push_back(c[i]+1);
    if(a[i]+n<2*n) bs[a[i]+n].push_back(c[i]+1);
    bs[b[i]].push_back(c[i]+2);
    if(b[i]+n<2*n) bs[b[i]+n].push_back(c[i]+2);
  }

  ll mn=INF;
  rep(i,2*n-1){
    for(ll bb : bs[i]){
      minch(mn,bb);
    }
    es.push_back((edge){i%n,(i+1)%n,mn});
    mn+=2;
  }

  sort(all(es),[](const edge& a,const edge& b){
    return a.cost < b.cost;
  });

  ll res=0;
  UnionFind uf(n);
  rep(i,es.size()){
    if(uf.unite(es[i].u,es[i].v)){
      res+=es[i].cost;
    }
  }

  cout<<res<<endl;

  return 0;
}
