#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
#define fre(x) freopen(x".in","r",stdin),freopen(x".out","w",stdout)
using namespace std;

inline int read(){
	int sum=0,f=1;char ch=getchar();
	while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0' && ch<='9'){sum=sum*10+ch-'0';ch=getchar();}
	return f*sum;
}

const int N=200001;
struct edge{int x,y;ll w;}a[N<<1];
int n,m,tot,fa[N];ll f[N],ans;

inline void add(int x,int y,ll z){
	a[++tot]=(edge){x,y,z};
}

inline int find(int x){return x==fa[x]? x:fa[x]=find(fa[x]);}

inline bool cmp(edge a,edge b){return a.w<b.w;}

int main(){
	n=read();m=read();
	for(int i=1;i<=n;i++) fa[i]=i;
	memset(f,0x3f,sizeof(f));
	while(m--){
		int x=read()+1,y=read()+1;ll z=read();
		add(x,y,z);f[x]=min(f[x],z+1);f[y]=min(f[y],z+2);
	}
	for(int i=1;i<=(n<<1);i++) f[i%n+1]=min(f[i%n+1],f[(i-1)%n+1]+2);
	for(int i=1;i<=n;i++) add(i,i%n+1,f[i]);
	sort(a+1,a+tot+1,cmp);
	for(int i=1;i<=tot;i++){
		int aa=find(a[i].x),b=find(a[i].y);
		if(aa!=b) ans+=a[i].w,fa[aa]=b;
	}
	printf("%lld\n",ans);
	return 0;
}
