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

const int INF = 1e9 + 7;
const long long INFM = 1e18 + 10;
const int N = 20;
bool vis[N];
int per[N];
long long curr = 0;
long long MX = INFM;

void f(int pos, int n, vector < int > & c, vector < int > & b, int m)
{
  if(pos >= n)
  {
    //for(int i =  0; i < n; i++) cout << per[i] << " ";
    //cout << "\n";
    curr = 0;
    for(int i = 0; i < n; i++) curr += min(abs(c[per[i] - 1] - b[i]), m - abs(c[per[i] - 1] - b[i]));
    MX = min(MX, curr);
    return;
  }

  for(int i = 1; i <= n; i++)
  {
    if(vis[i]) continue;
    vis[i] = true;
    per[pos] = i;
    f(pos + 1, n, c, b, m);
    per[pos] = 0;
    vis[i] = false;
  }
  return;
}
long long Konflikt(int N,int M,int *A,int *B)
{
  int n = N; int m = M;
  vector < int > a(n);
  for(int i = 0; i < n; i++) a[i] = A[i + 1];
  vector < int > b(n);
  for(int i = 0; i < n; i++) b[i] = B[i + 1];

  if(n <= 10 && m <= 20)
  {
    vector < int > cnt(m + 10, 0);
    vector < int > c;
    long long ans = INFM;
    for(int d = 0; d < m; d++)
    {
      for(auto it : a) cnt[(it + d) % m]++;
      for(int i = 0; i < m; i++) for(int j = 0; j < cnt[i]; j++) c.push_back(i);

      f(0, n, c, b, m);
      ans = min(ans, MX);

      for(int i = 0; i < m; i++) cnt[i] = 0;
      c.clear();
      MX = INFM;
    }
    return ans;
  }
  return 0;
}