#include <bits/stdc++.h>
using namespace std;
int a[5005], b[5005];
int mat[505][505];
void ispis(int n){
    for(int i = 1; i<=n; i++){
        for(int j = 1; j<=n; j++){
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}
long long Konflikt(int N,int M,int *A,int *B){
    long long best = 7777777, tren = 0;
    for(int i = 0; i<M; i++){
    for(int j = 1; j<=N; j++){
        a[j] = (A[j]+i)%M;
        //cout << a[j] << " ";
        b[j] = B[j];
    }
    for(int j = 1; j<=N; j++){
        int mn = 67676767, k1;
        for(int k = 1; k<=N; k++){
              // cout << j << " " << k << " " << abs(a[j]-b[k]) << " " << M-abs(a[j]-b[k]) << endl;
                mn = min(abs(a[j]-b[k]), M-abs(a[j]-b[k]));
               // cout << mn << " ";
                mat[j][k] = mn;

        }
        //cout << abs(a[1]-b[2]) << endl;
        //cout << mn << " " << j << " " << k1 << endl;
       /// cout << "Mn:" << mn << endl;
    }
    //ispis(N);
    for(int i1 = 1; i1<=N; i1++){
            int mn = 67676767, j1;
        for(int j = 1; j<=N; j++){
            if(mat[i1][j]<mn && mat[i1][j]!=-1){ mn = mat[i1][j];
            j1 = j;
            }
        }
        for(int l = 1; l<=N; l++){
            if(l==i1) continue;
            mat[l][j1] = -1;
        }
        for(int l = 1; l<=N; l++){
            if(l==j1) continue;
            mat[i1][l] = -1;
        }
        tren+=mn;
    }
   // cout << endl << tren << endl;
    //if(tren==2) cout << i << endl;
    if(tren<best) best = tren;
    tren = 0;
    }
    return best;
}