#include <bits/stdc++.h>

using namespace std;

long long Konflikt(int N,int M,int *A,int *B){
    if(N>1000) return 0;
    #define int long long
    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;
}