#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll dist(ll a, ll b, ll M) {
	return min(abs(a-b), M - abs(a-b));
}

long long Konflikt(int N,int M,int *A,int *B) {
	ll tmp[N+1], minres = LLONG_MAX;
	sort(A+1, A+N+1);
	sort(B+1, B+N+1);
	for(ll m = 1; m <= N; m++) {
		ll res = 0ll;
		ll mod = B[m] - A[1];
		for(int i = 1; i <= N; i++) {
			tmp[i] = (A[i] + m) % M;
			res += dist(tmp[i], B[i], M);
		}
		minres = min(minres, res);
		for(int i = 1; i <= N; i++) {
			res = 0;
			for(int j = 1; j <= i; j++) {
				res += dist(tmp[j], B[N-j+1], M);
			}
			for(int j = i+1; j <= N; j++) {
				res += dist(tmp[j], B[j-i], M);
			}
			minres = min(minres, res);
		}
	}
	if(minres == LLONG_MAX)
		return 0ll;
	return minres;
}