#include <bits/stdc++.h>

using namespace std;

long long Konflikt(int N,int M,int *A,int *B){
    long long minDist = INT64_MAX;
    bool* bio = (bool*)calloc((N+1), sizeof(bool));
    for(int k=0;k<M;k++){
        long long s = 0;
        for(int i=0;i<=N;i++) bio[i]=false;
        for(int i=1;i<=N;i++){
            long long dist = INT64_MAX;
            int ind = -1;
            for(int j=1;j<=N;j++){
                if(bio[j]) continue;

                long long newdist = min(dist, (long long)min(abs(A[i]-B[j] + k), M- abs(A[i]-B[j] + k)));
                if(newdist!=dist){
                    dist = newdist;
                    ind = j;
                }
            }
            bio[ind] = true;
            s+=dist;
        }
        minDist = min(minDist, s);
    }
    return minDist;

}