#include <bits/stdc++.h>
#define int long long
#define inf 0x3f3f3f3f
#define re register
#define N 301200
#define pii pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define mod 1000000007
using namespace std;
struct edge{
	int u,v,d;
}e[N<<1];
inline int read(){
	int x=0,w=0;char ch=getchar();
	while (!isdigit(ch))w|=ch=='-',ch=getchar();
	while (isdigit(ch))x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
	return w?-x:x;
}
int f[N],g[N],ans,n,Q,cnt;
inline bool cmp(edge a,edge b){
	return a.d<b.d;
}
int find(int k){return f[k]==k?k:f[k]=find(f[k]);}
void Kr(){
	sort(e+1,e+1+cnt,cmp);
	for (int i=1,t=0;i<=cnt;++i){
		int x=find(e[i].u),y=find(e[i].v);
		if (x==y)continue;
		f[x]=y;
		++t;ans+=e[i].d;
		if (t==n-1)break;
	}
}
signed main(){
	n=read(),Q=read();
	memset(g,0x3f,sizeof(g));
	while (Q--){
		int u=read()+1,v=read()+1,d=read();
		e[++cnt]=(edge){u,v,d};
		g[u]=min(g[u],d+1);g[v]=min(g[v],d+2);
	}
	for (int i=1;i<=n;++i)
		g[i%n+1]=min(g[i%n+1],g[i]+2),f[i]=i;
	for (int i=1;i<=n;++i)
		g[i%n+1]=min(g[i%n+1],g[i]+2);
	for (int i=1;i<=n;++i)e[++cnt]=(edge){i,i%n+1,g[i]};
	Kr();
	printf("%lld\n",ans);
	return 0;
}