#include <bits/stdc++.h>

using namespace std;
using ll = long long;
long long Konflikt(int N,int M,int *A,int *B){
    ll ans = 1e18;
    auto dist = [&](int x, int y) {
        return min(abs(x-y), M-abs(x-y));
    };
    if (N > 600*600/M)  return 0;
    for (int X = 0; X < M; ++X) {
        ll s = 0;
        set<int> a, b;
        for (int i = 1; i <= N; ++i) {
            A[i]++;
            if (A[i] == M)  A[i] = 0;
            a.insert(A[i]), b.insert(B[i]);
        }
        int aa, bb;
        for (int i = 0; i < N; ++i) {
            aa = -1, bb = -1;
            for (auto x : a) {
                for (auto y : b) {
                    if (aa == -1 || dist(aa, bb) > dist(x, y))  aa = x, bb = y;
                }
            }
            a.erase(aa);
            b.erase(bb);
            //cout << aa << ' ' << bb << '\n';
            s += dist(aa, bb);
        }
        //cout << s << "\n\n\n";
        ans = min(ans, s);
    }
    return ans;
}
/*
3 20
0 6 2
5 19 7
*/