This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//______________"In The Name Of GOD"______________
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <ll, ll> pll;
typedef pair <int, int> pii;
const int lg        = 20;
const int mod       = 1e9 + 7;
const ll  inf       = 1e9 + 100;
const int maxn      = 3e3 + 100;
    
#define cl       	clear
#define F        	first
#define S       	second
#define pb       	push_back
#define Sz(x)    	int((x).size())
#define all(x)   	(x).begin(), (x).end()
int a[maxn], b[maxn], ps[maxn], q, n;
vector <int> vc[maxn];
multiset <int> s;
inline int cal(int ind){
    fill(ps, ps + n, 0);
    for(int i = 0; i < q; i ++) a[i] = (a[i] - ind + n) % n, b[i] = (b[i] - ind + n) % n;
    for(int i = 0; i < q; i ++) {
        ps[min(a[i], b[i])] ++;
        ps[max(a[i], b[i])] --;
        vc[min(a[i], b[i])].pb(max(a[i], b[i]));
    }
    int ans = 0;
    for(int i = 0; i < n; i ++){
        while(!s.empty() && *s.begin() == i) s.erase(s.begin());
        if(i) ps[i] += ps[i - 1];
        for(auto x : vc[i]) s.insert(x);
        while(!s.empty() && ps[i] > 0){
            int t = *s.rbegin();
            ps[i] -= 2, ps[t] += 2;
            s.erase(s.find(t));
            ans ++;
        }
    }
    for(int i = 0; i < q; i ++) a[i] = (a[i] + ind + n) % n, b[i] = (b[i] + ind + n) % n;
    return ans;
}
int main(){
    ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0);
    cin >> n >> q;
    for(int i = 0, c; i < q; i ++) cin >> a[i] >> b[i] >> c, a[i] --, b[i] --;
    int ans = inf;
    for(int i = 0; i < n; i ++) ans = min(ans, cal(i));
    cout << ans << '\n';
    return 0;
}
/*test case :
*/
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |