#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define ll long long
#define ld long double
#define mp make_pair
template<typename T1,typename T2>void chmn(T1 &x,const T2 &y){x=x<y?x:y;}
template<typename T1,typename T2>void chmx(T1 &x,const T2 &y){x=x<y?x:y;}
const int N=5010;
const ll INF=1e18;
int a[N],b[N],n,L;
ll Calc(int x,int y){
    ll res=0;
    for(int i=0;i<n;i++){
        int X=((a[i]+y-b[(i+x)%n])%L+L)%L;
        res+=min(X,L-X);
    }
    return res;
}
ll Konflikt(int n1,int L1,int *A,int *B){
    n=n1,L=L1;
    for(int i=0;i<n;i++)a[i]=A[i+1],b[i]=B[i+1];
    sort(a,a+n);
    sort(b,b+n);
    ll res=INF;
    for(int i=0;i<n;i++){
        int l=0,r=L-1;
        while(l<r){
            int mid=l+r>>1;
            if(Calc(i,mid)<=Calc(i,mid+1))r=mid;
            else l=mid+1;
        }
        chmn(res,Calc(i,l));
    }
    return res;
}