#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;}
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx")
const int N=5010,S=7;
const ll INF=1e18;
int a[N],b[N],n,L;
ll res;
ll Calc(int x,int y){
    ll ans=0;
    for(int i=0;i<n;i++){
        int X=abs((a[i]+y)%L-b[(i+x)%n]);
        ans+=min(X,L-X);
    }
    chmn(res,ans);
    return ans;
}
ll Get(int 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;
    }
    return Calc(i,l);
}
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);
    res=INF;
    //for(int i=0;i<n;i++)printf("%lld ",Get(i));printf("\n");
    /*int l=0,r=n-1;
    while(r-l+1>=40){
        int d=(r-l+1)/4;
        if(Get(l+d-1)<=Get(r-d+1))r=r-d+1;
        else l=l+d-1;
    }
    for(int i=l;i<=r;i++)Get(i);
    for(int i=0;i<min(20,n);i++)Get(i);
    for(int i=n-1;i>max(0,n-20);i--)Get(i);*/
    ll mn=1e18;int idx=-1;
    for(int i=0;i<n;i+=S){
        ll x=Get(i);
        if(x<mn){mn=x,idx=i;}
    }
    for(int i=idx-80;i<=idx+80;i++)if(0<=i&&i<n)Get(i);
    if(n<=700)for(int i=0;i<n;i++)Get(i);
    return res;
}