#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<bitset>
#include<string>
#include<cstdio>
#include<cctype>
#include<cassert>
#include<cstdlib>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>
 
#define For(i,x,y) for (int i=x;i<y;i++)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
 
#define dprintf(...) fprintf(stderr,__VA_ARGS__)
using namespace std;
 
int IN(){
	int c,f,x;
	while (!isdigit(c=getchar())&&c!='-');c=='-'?(f=1,x=0):(f=0,x=c-'0');
	while (isdigit(c=getchar())) x=(x<<1)+(x<<3)+c-'0';return !f?x:-x;
}
 
typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef vector<int> Vi;
 
const int N=400000+19;
const ll oo=1ll<<40;
 
struct Edge{
	int x,y;
	ll z;
	bool operator < (const Edge &B) const {return z<B.z;}
} E[N];
int fa[N];
ll val[N],tmp=oo;
int n,m,Qc,A,B,C;
 
int getf(int x){
	return fa[x]==x?x:fa[x]=getf(fa[x]);
}
ll Kruskal(){
	ll res=0;
	For(i,0,n) fa[i]=i;
	sort(E,E+m);
	For(i,0,m){
		int x=getf(E[i].x),y=getf(E[i].y);
		if (x!=y) fa[x]=y,res+=E[i].z;
	}
	return res;
}
 
int main(){
	n=IN();Qc=IN();
	For(i,0,n) val[i]=oo;
	while (Qc--){
		A=IN(),B=IN(),C=IN();
		E[m++]=(Edge){A,B,C};
		val[A]=min(val[A],C+1ll);
		val[B]=min(val[B],C+2ll);
	}
	for (int i=0,x=0;i<3*n;i++,x=(x+1)%n){
		val[x]=min(val[x],tmp);
		tmp=min(tmp,val[x])+2;
	}
	For(i,0,n) E[m++]=(Edge){i,(i+1)%n,val[i]};
	cout<<Kruskal()<<endl;
}