#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 i = 1; i <= N; ++i) {
        for (int j = 1; j <= N; ++j) {
            int a[N+1], b[N+1];
            for (int k = 1; k <= N; ++k)    a[k] = (A[k]+B[j]-A[i]+M)%M, b[k] = B[k];
            sort(a+1, a+N+1, [&](int x, int y) {
                    return (x-B[j]+M)%M < (y-B[j]+M)%M;
                 });
            sort(b+1, b+N+1, [&](int x, int y) {
                    return (x-B[j]+M)%M < (y-B[j]+M)%M;
                 });
            ll s = 0;
            for (int k = 1; k <= N; ++k)    s += dist(a[k], b[k]);
            ans = min(ans, s);
        }
    }
    if (N > 500)    return 0;
    return ans;
}
/*
3 20
0 6 2
5 19 7
*/