#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define re register
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi()
{
	int f=1,sum=0;char ch=getchar();
	while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
	return f*sum;
}
const int N=400010;
int val[N],n,q,cnt,f[N];
ll ans;
struct node
{
	int u,v,w;
	bool operator<(const node&b)const
		{
			return w<b.w;
		}
}e[N<<1];
int find(int x)
{
	if(f[x]!=x)f[x]=find(f[x]);
	return f[x];
}
int main()
{
	n=gi();q=gi();
	memset(val,127,sizeof(val));
	for(int i=1;i<=q;i++)
	{
		int a=gi(),b=gi(),c=gi();
		e[++cnt]=(node){a,b,c};
		val[a]=min(val[a],c+1);
		val[b]=min(val[b],c+2);
	}
	int pos=0;
	for(int i=1;i<n;i++)if(val[pos]>val[i])pos=i;
	for(int i=(pos+1)%n,j=pos;i!=pos;j=i,i=(i+1)%n)
		val[i]=min(val[i],val[j]+2);
	for(int i=0;i<n-1;i++)
		e[++cnt]=(node){i,i+1,val[i]};
	e[++cnt]=(node){n-1,0,val[n-1]};
	sort(e+1,e+cnt+1);
	for(int i=0;i<n;i++)f[i]=i;
	int k=0;
	for(int i=1;i<=cnt;i++)
	{
		int u=e[i].u,v=e[i].v;
		if(find(u)!=find(v))
		{
			ans+=e[i].w,f[find(u)]=find(v);
			k++;
			if(k==n-1)break;
		}
	}
	printf("%lld\n",ans);
	return 0;
}
