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

typedef long long ll;
#define MAXN 500
#define INF 1000000007

ll sve[MAXN][MAXN];

ll checkall(int x, int N, int d, int bitmask, ll sum) {
	ll minn = INF;
	if (d == N) {
		return sum;
	}
	for (int c = 1; c <= N; c++) {
		if (bitmask & (1<<c)) {
			continue;
		}
		minn = min(minn,checkall(x,N,d+1,bitmask + (1<<c),sum + abs(sve[c][d+1]+x)));
	}
	return minn;
}

long long Konflikt(int N,int M,int *A,int *B) {
	for (int i = 1; i <= N; i++) {
		for (int j = 1; j <= N; j++) {
			sve[i][j] = min(abs(A[i]-B[j]), M - abs(A[i]-B[j]));
			if (A[i] < B[j]) {
				if (sve[i][j] == abs(A[i]-B[j])) {
					sve[i][j] *= -1;
				}
			} else {
				if (sve[i][j] == M - abs(A[i]-B[j])) {
					sve[i][j] *= -1;
				}
			}
		}
	}
	ll minn = INF;
	for (int x = 0; x < M; x++) {
		minn = min(minn,checkall(x,N,0,0,0));
	//	cout << minn << ' ' << x << endl;
	}
	for (int i = 1; i <= N; i++) {
		for (int j = 1; j <= N; j++) {
		//	cout << sve[i][j] << ' ';
		}
	//	cout << endl;
	}
	return minn
	;
}