#include <bits/stdc++.h>
#define Set(a, b) memset(a, b, sizeof (a))
#define For(i, j, k) for (int i = j; i <= k; ++ i)
#define Forr(i, j, k) for (int i = j; i >= k; -- i)
using namespace std;
typedef long long ll;
inline int read() {
int x = 0, p = 1; char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') p = -1;
for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * p;
}
template <typename T> inline bool chkmin(T &a, T b) { return a > b ? a = b, 1 : 0; }
inline void File() {
freopen("g.in", "r", stdin);
freopen("g.out", "w", stdout);
}
const int N = 2e5 + 10, inf = 0x3f3f3f3f;
int n, m, fa[N], cnt, val[N];
struct edge {
int u, v, w;
bool operator < (const edge &rhs) const {
return w < rhs.w;
}
} E[N << 1];
int find(int x) {
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main() {
Set(val, inf);
n = read(), m = read();
For(i, 1, m) {
int u = read(), v = read(), w = read();
chkmin(val[u], w + 1), chkmin(val[v], w + 2);
E[++ cnt] = (edge) {u, v, w};
}
For(i, 1, n << 1) chkmin(val[i % n], val[(i - 1) % n] + 2);
For(i, 0, n - 1) E[++ cnt] = (edge) {i, i == n - 1 ? 0 : i + 1, val[i]}, fa[i] = i;
sort(E + 1, E + 1 + cnt);
int c = 0; ll ans = 0;
For(i, 1, cnt) {
int u = find(E[i].u), v = find(E[i].v);
if (u ^ v)
++ c, ans += E[i].w; fa[u] = v;
if (c == n - 1) break;
}
cout << ans << endl;
return 0;
}