#include <bits/stdc++.h>
using namespace std;
using ll = long long;
long long Konflikt(int N,int M,int *A,int *B)
{
    ll n=N,res=1e18,x,i,dist1,dist2,j,dist11,dist22;
    for(x=0;x<=M-1;x++)
    {

        vector<ll>napad(n),novepoz(n);
        for(i=0;i<n;i++)
        {
            napad[i]=i;
        }
        for(i=0;i<n;i++)
        {
            novepoz[i]=(A[i+1]+x)%M;
        }
        for(i=0;i<n;i++)
        {
            dist1=min(M-abs(novepoz[i]-B[napad[i]+1]),abs(novepoz[i]-B[napad[i]+1]));
            for(j=i+1;j<n;j++)
            {
                dist2=min(M-abs(novepoz[j]-B[napad[j]+1]),abs(novepoz[j]-B[napad[j]+1]));

                dist11=min(M-abs(novepoz[i]-B[napad[j]+1]),abs(novepoz[i]-B[napad[j]+1]));
                dist22=min(M-abs(novepoz[j]-B[napad[i]+1]),abs(novepoz[j]-B[napad[i]+1]));

                if(dist11+dist22<dist1+dist2)
                {

                    swap(napad[i],napad[j]);
                }
            }

        }
      //  cout << endl;
        ll trenres=0;
        for(i=0;i<n;i++)
        {
            trenres+=min(M-abs(novepoz[i]-B[napad[i]+1]),abs(novepoz[i]-B[napad[i]+1]));
         //   cout << min(M-abs(novepoz[i]-B[napad[i]+1]),abs(novepoz[i]-B[napad[i]+1])) << endl;
        }


        res=min(res,trenres);
    }
    return res;
}