#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define pi pair<int, int>
#define pl pair<ll, ll>
#define f first
#define s second
#define vi vector<int>
#define vl vector<ll>
#define vvi vector<vi>
#define vvl vector<vl>
#define vpl vector<pl>
#define vpi vector<pi>
#define sz(x) x.size()
#define FOR(i,a,b) for(ll i=(a);i<(b);i++)
#define F0R(i,a) FOR(i,0,(a))
#define ROF(i,a,b) for(ll i=(b)-1;i>=(a);i--)
#define R0F(i,a) ROF(i,0,(a))
#define trav(el, v) for(auto &el : v)
#define nl endl
#define end(v) v.end()
#define bg(v) v.begin()
#define pb push_back
#define all(v) bg(v),end(v)
#define sor(v) sort(all(v))

ll INF = 1e18;

ll sol = INF;
vl a(5005), b(5005);
int n, m;

void solve(){
    vl p, ne;
    ll cnt = 0, cur = 0;
    FOR(i, 1, n + 1){
        int x = abs(a[i] - b[i]), y = m - x;
        if(a[i] > b[i]){
            if(x < y)ne.pb(x);
            else p.pb(y);
        }
        else if(a[i] < b[i]){
            if(x < y)p.pb(x);
            else ne.pb(y);
        }
        else cnt++;
        cur += min(x, y);
    }
    if(sz(p) > sz(ne)){
        int x = sz(p), y = sz(ne) + cnt, i = 0;
        ll bef = 0;
        sor(p);
        //cerr << "poz: ";
        //trav(el, p)cerr << el << " ";
        //cerr << nl;
        while(x > y){
            //cerr << "1 " << x << " " << y << nl;
            cur -= (p[i] - bef) * (x - y);
            bef = p[i];
            x--;
            y++;
        }
    }
    else{
        int x = sz(ne), y = sz(p) + cnt, i = 0;
        ll bef = 0;
        sor(ne);
        //cerr << "neg: ";
        //trav(el, ne)cerr << el << " ";
        //cerr << nl;
        while(x > y){
            //cerr << "2 " << x << " " << y << nl;
            cur -= (ne[i] - bef) * (x - y);
            bef = ne[i];
            x--;
            y++;
        }
    }
    //cerr << cur << nl;
    sol = min(sol, cur);
}

long long Konflikt(int N,int M,int *A,int *B){
    n = N;
    m = M;
    FOR(i, 1, n + 1)a[i] = A[i];
    FOR(i, 1, n + 1)b[i] = B[i];
    int d = b[1];
    FOR(i, 1, n + 1)b[i] -= d;
    FOR(i, 1, n + 1){
        int d2 = m - a[n];
        ROF(j, 1, n)a[j + 1] = a[j] + d2;
        a[1] = 0;
        //FOR(j, 1, n + 1)cerr << a[j] << " ";
        //cerr << nl;
        //FOR(j, 1, n + 1)cerr << b[j] << " ";
        //cerr << nl;
        solve();
    }
    //cerr << "hi";
    //solve();
    //cerr << sol << nl;
    return sol;
}


/*
3 10
4 5 6
1 2 3

5 42
0 13 18 20 35
0 5 11 29 39


*/