#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));
    };
    for (int X = 0; X < M; ++X) {
        for (int i = 1; i <= N; ++i) {
            A[i]++;
            if (A[i] == M)  A[i] = 0;
        }
        vector<int> p(N);
        iota(p.begin(), p.end(), 1);
        do {
            ll s = 0;
            for (int i = 1; i <= N; ++i) {
                s += dist(A[p[i-1]], B[i]);
            }
            ans = min(ans, s);
        } while(next_permutation(p.begin(), p.end()));
    }
    return ans;
}
/*
3 20
0 6 2
5 19 7
*/