#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 5005;
int m;
int dif(int a, int b){return (a-b+m)%m;}


int n;
int a[MAXN], b[2*MAXN];

int calc(int of){
    vector<int> v = {0};
    for(int i = 2; i <= n; ++i){
        v.push_back(dif(a[i],a[1])-dif(b[i+of],b[1+of]));
    }
    //for(int k : v) cout << k << ' '; cout << '\n';
    sort(v.begin(), v.end());
    int ln = v.size();
    int tmp = v[ln/2];
    int ans = 0;
    for(int i = 0; i < ln; ++i){
        v[i] -= tmp;
        ans += abs(v[i]);
    }
    return ans;
}

long long Konflikt(int32_t N,int32_t M,int32_t *A,int32_t *B){
    n = N;
    m = M;
    for(int i = 1; i <= n; ++i){
        a[i] = A[i];
        b[i] = B[i];
    }
    sort(a+1, a+n+1);
    sort(b+1, b+n+1);
    for(int i = 1; i <= n; ++i){
        b[n+i] = b[i];
    }
    int ans = 1e18;
    for(int i = 0; i < n; ++i){
        ans = min(ans, calc(i));
    }
    return ans;
}
#undef int