#include <bits/stdc++.h>

using namespace std;

long long Konflikt(int N,int M,int *A,int *B){
    if(N>500 && M>500) return 0;
    #define int long long
    if(M>500){
    sort(B+1,B+N+1);
    int minn = 1e18;
    for(int p = 0; p<M;p++){
        sort(A+1, A+N+1);
        if(p!=A[1]-B[1] && p!=M-(A[1]-B[1])) continue;
        int C[N+1];
        for(int i=1;i<=N;i++) C[i] = (A[i]+p)%M;
        sort(C+1, C+N+1);
        int trmin = 1e18;
        for(int j=0;j<N;j++){
            int rez = 0;
            for(int i=1;i<=N;i++){
                rez+=min(abs(C[(i+j-1)%N+1] - B[i]), M-abs(C[(i+j-1)%N+1] - B[i]));
            }
            trmin = min(trmin, rez);
        }
        minn = min(trmin, minn);
    }
    return minn;
    }
    sort(B+1,B+N+1);
    int minn = 1e18;
    for(int p = 0; p<M;p++){
        int C[N+1];
        for(int i=1;i<=N;i++) C[i] = (A[i]+p)%M;
        sort(C+1, C+N+1);
        int trmin = 1e18;
        for(int j=0;j<N;j++){
            int rez = 0;
            for(int i=1;i<=N;i++){
                rez+=min(abs(C[(i+j-1)%N+1] - B[i]), M-abs(C[(i+j-1)%N+1] - B[i]));
            }
            trmin = min(trmin, rez);
        }
        minn = min(trmin, minn);
    }
    return minn;
}