#include <bits/stdc++.h>

using namespace std;

long long Konflikt(int N,int M,int *A,int *B)
{
	int n = N; int m = M;
	vector<int> a = vector<int>(n);
	vector<int> izm = vector<int>(n);
	vector<int> b = vector<int>(n);
	for	(int i = 0; i < n; i++)
	{
		a[i] = A[i + 1];
		b[i] = B[i + 1];
	}
	sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    long long ans = 1e18;
	for(int i = 0; i < n; i++)
	{
		vector<long long> rast = vector<long long>(n);
		for(int j = 0; j < n; j++)
        {
            int ind = (i + j) % n;
            ///if(0 <= a[ind] - b[j] && a[ind] - b[j] <= (m + 1) / 2) rast[j] = a[ind]- b[j];
            ///else if (0 <= a[ind] - b[j] && a[ind] - b[j] > (m + 1) / 2) rast[j] = m - (b[j] - a[ind]);
            ///else if(0 >= a[ind] - b[j] && b[j] - a[ind] <= (m + 1) / 2) rast[j] = b[j] - a[ind];
            ///else if (0 >= a[ind] - b[j] && b[j] - a[ind] > (m + 1) / 2) rast[j] = m - (a[ind] - b[j]);
            rast[j] = abs(b[j] - a[ind]);
        }
        sort(rast.begin(), rast.end());
        long long s1 = 0;
        for(int j = 0; j < n; j++)
        {
            ///cout << rast[j] << " ";
            s1 += abs(rast[n - 1 -j] - rast[j]);
        }
        s1 /= 2;
        ///cout << "\n";
        if(ans > s1) ans = s1;
        for(int j = 0; j < n; j++)
        {
            if(rast[j] >= (m + 1) / 2) rast[j] = m - rast[j];
        }
        s1 = 0;
        sort(rast.begin(), rast.end());
        for(int j = 0; j < n; j++)
        {
            ///cout << rast[j] << " ";
            s1 += abs(rast[n - 1 -j] - rast[j]);
        }
        s1 /= 2;
        ///cout << "\n";
        if(ans > s1) ans = s1;
	}
	return ans;
}