#include <bits/stdc++.h>
using namespace std;
long long Konflikt(int N,int M,int *A,int *B){
    deque <int> ns;
    deque <int> ms;
    int i,j,x,pm;
    long long res=9999999999999, p;
    for(j=0;j<M;j++)
    {
        x=j;
        p=0;
        for(i=1;i<=N;i++)
        {
            ms.push_back((A[i]+x)%M);
            ns.push_back((B[i]+x)%M);
        }
        stable_sort(ns.begin(),ns.end());
        stable_sort(ms.begin(),ms.end());
        while(!ns.empty() && p<res)
        {
            if(ns.size()==1)
            {
                p+=min(abs(ms[0]-ns[0]),M-abs(ms[0]-ns[0]));
                ns.pop_front();
                ms.pop_front();
            }
            else
            {
                if(min(abs(ms[0]-ns[0]),M-abs(ms[0]-ns[0]))<=min(abs(ms[1]-ns[0]),M-abs(ms[1]-ns[0])))
                {
                    p+=min(abs(ms[0]-ns[0]),M-abs(ms[0]-ns[0]));
                    ns.pop_front();
                    ms.pop_front();
                }
                else
                {
                    p+=min(abs(ms[1]-ns[0]),M-abs(ms[1]-ns[0]));
                    pm=ms[0];
                    ns.pop_front();
                    ms.pop_front();
                    ms[0]=pm;
                }
            }
        }
        if(p<res)
        {
            res=p;
        }
    }
    return res;
}