#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long 
struct r{
	int u,v,w;
}e[400050];
int w[400050],fa[200050],cnt,n,m;
ll ans;
int get_fa(int u){return fa[u]==u ? u:fa[u]=get_fa(fa[u]);}
bool cmp(r a,r b){return a.w<b.w;}
int main(){
	scanf("%d%d",&n,&m);
	memset(w,127,sizeof w);
	for (int i=1;i<=m;i++){
		scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
		w[e[i].u]=std::min(w[e[i].u],e[i].w+1);
		w[e[i].v]=std::min(w[e[i].v],e[i].w+2);
	}
	for (int i=0;i<n;i++) fa[i]=i;
	for (int i=1;i<(n<<1);i++)
		w[i]=std::min(w[i],w[i-1]+2);
	for (int i=0;i<n;i++)
		e[++m]=(r){i,(i+1)%n,std::min(w[i],w[i+n])};
	std::sort(e+1,e+m+1,cmp);
	for (int i=1;i<=m;i++){
		if (get_fa(e[i].u)==get_fa(e[i].v)) continue;
		fa[e[i].v]=fa[e[i].u];
		ans+=1ll*e[i].w;
		cnt++;
		if (cnt==n-1) {
			printf("%lld",ans);
			return 0;
		}
	}
} 