#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) {
	if(N > 10 || N == 0)
		return 0ll;
	ll tmp[N+1], minres = LLONG_MAX;
	for(ll m = 0; m < M; m++) {
		ll res = 0ll;
		for(int i = 1; i <= N; i++) {
			tmp[i] = (A[i] + m) % M;
		}
		sort(tmp+1, tmp+N+1);
		do {
			res = 0ll;
			for(int i = 1; i <= N; i++) {
				res += dist(tmp[i], B[i], M);
			}
			minres = min(minres, res);
		} while(next_permutation(tmp+1, tmp+N+1));
	}
	return minres;
}