#include <algorithm>

using namespace std;

long long Konflikt(int N, int M, int *A, int *B) {
	sort(A + 1, A + N + 1);
	sort(B + 1, B + N + 1);
	
	long long najmanjaDistanca = (1ll << 62);
	for(int X = 0; X < M; X++) {
		int najbliziNisu = (1 << 30);
		for(int i = 1; i <= N; i++) {
			long long distanca = 0;
			for(int j = 1; j <= N; j++) {
				int p = B[(i + j - 2) % N + 1];
				int q = (A[j] + X) % M;
				distanca += min(abs(p - q), M - abs(p - q));
				
				if(q < p) najbliziNisu = min(najbliziNisu, p - q);
				else      najbliziNisu = min(najbliziNisu, M - (q - p));
			}
			najmanjaDistanca = min(najmanjaDistanca, distanca);i=N-1;
		}
	}
	
    return najmanjaDistanca;
}