#include <bits/stdc++.h>
using namespace std;
using ll = long long;

vector<ll> pomeri(vector<ll>& a,ll m){
    vector<ll> ans;
    for(int i =0; i < a.size(); i++){
        ans.push_back((a[i]+1)%m);


    }
    return ans;
}

ll dist(vector<int>&a,int ml);

long long Konflikt(int N,int M,int *A,int *B){
    ll n,m;
    n = N;m = M;


    vector<ll> a(n),b(n);
    for(int i = 0; i < n; i++)a[i] = A[i+1];
    for(int i = 0; i < n; i++)b[i] = B[i+1];
    sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    ll ans = 1e18;
    if(m <= 500){


        int t = m;
        while(t--){
            ll l = 0;
            ll r = 0;
            for(int i = 0; i < n; i++){
                l += min(abs(a[i] - b[i]),m - abs(a[i]-b[i]));
            }
            r += min(abs(a[0] - b[n-1]),m - abs(a[0] - b[n-1]));



            for(int i =1;  i< n; i++){
                r += min(abs(a[i]-b[i-1]),m - abs(a[i]-b[i-1]));
            }
            //cout << l << " " << r << " <-- l r \n";
            //for(int i = 0; i < n; i++){
            //    cout << a[i] << " ";
            //}
            //cout << '\n';

            ans = min(ans,min(l,r));


            a = pomeri(a,m);
        }
        return ans;

    }




}