Problem:
Tally Counters
A number of tally counters are placed in a row.
Pushing the button on a counter will increment the displayed value by one, or, when the value is already the maximum, it goes down to one.
All the counters are of the same model with the same maximum value.
Fig. D-1 Tally Counters
Starting from the values initially displayed on each of the counters, you want to change all the displayed values to target values specified for each.
As you don't want the hassle, however, of pushing buttons of many counters one be one, you devised a special tool.
Using the tool, you can push buttons of one or more
adjacent counters, one push for each, in a single operation.
You can choose an arbitrary number of counters at any position in
each operation, as far as they are consecutively lined up.
How many operations are required at least to change the displayed values on counters to the target values?
Input
The input consists of multiple datasets, each in the following format.
n
m
a
1
a
2
...
a
n
b
1
b
2
...
b
n
Each dataset consists of 3 lines.
The first line contains
n
(1 ≤
n
≤ 1000) and
m
(1 ≤
m
≤ 10000), the number of counters and the maximum value displayed on counters, respectively.
The second line contains the initial values on counters,
a
i
(1 ≤
a
i
≤
m
), separated by spaces.
The third line contains the target values on counters,
b
i
(1 ≤
b
i
≤
m
), separated by spaces.
The end of the input is indicated by a line containing two zeros.
The number of datasets does not exceed 100.
Output
For each dataset, print in a line the minimum number of operations required to make all of the counters display the target values.
Sample Input
4 5
2 3 1 4
2 5 5 2
3 100
1 10 100
1 10 100
5 10000
4971 7482 1238 8523 1823
3287 9013 9812 297 1809
0 0
Output for the Sample Input
4
0
14731

Submitted solutions:

code_snippet: /*
 *   author : cellul4r
 */
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;
#define all(x) x.begin(), x.end()
const char nl = '\n';
const int N =1e3+1;
const int INF = 1e9+7;
const ll LINF = 1e18+7;

const int dr[] = {-1,0,1,0}, dc[] = {0,1,0,-1};
void setIO(string);
int n,m;
ll a[N], b[N];
ll dp[N][N];
void solve(){
    
    cin>>n>>m;
    while(n != 0 || m != 0) {
        for(int i = 0; i < n; i++) cin>>a[i];
        for(int i = 0; i < n; i++) cin>>b[i];
        for(int i = 0; i < n; i++) {
            a[i] = (b[i] - a[i] + m) % m;
        }

        memset(dp, INF, sizeof dp);
        for(int i = 0; i <= n; i++) {
            dp[0][i] = a[0] + i * m; 
        }
        for(int i = 1; i < n; i++) {
            // x <= y
            // find min suffix of dp[i-1][k]
            // x > y
            // find min prefix of dp[i-1][k]
            vector<ll> pre(n+1), suff(n+1);
            pre[0] = dp[i-1][0];
            for(int k = 1; k <= n; k++) {
                pre[k] = min(pre[k-1], dp[i-1][k] - k * m);
            }

            suff[n] = dp[i-1][n];
            for(int k = n - 1; k >= 0; k--) {
                suff[k] = min(suff[k+1], dp[i-1][k]);
            }

            for(int j = 0; j <= n; j++) {
                //cerr << dp[i-1][j] << " ";
                ll x = a[i] + j * m;
                int l = 0, r = n+1;
                while(l < r) {
                    int mid = l + (r - l) / 2;
                    ll y = a[i-1] + mid * m;
                    if(y >= x) {
                        r = mid;
                    } else {
                        l = mid + 1;
                    }
                }
                if(l <= n) dp[i][j] = min(dp[i][j], suff[l]);
                if(l > 0) dp[i][j] = min(dp[i][j], pre[l-1] + x - a[i-1]);
                // O(n^3)
                /*for(int k = 0; k <= n; k++) {
                    ll y = a[i-1] + k * m;
                    if(x <= y) {
                        dp[i][j] = min(dp[i][j], dp[i-1][k]);
                    } else {
                        dp[i][j] = min(dp[i][j], dp[i-1][k] + x - y);
                    }
                }*/
            }
            //cerr << nl;
        }
        ll ans = LINF;
        for(int i = 0; i <= n; i++) {
            ans = min(ans, dp[n-1][i]);
        }
        cout << ans << nl;
        cin>>n>>m;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;

    //setIO("");
    //cin>>t;
    while(t--)solve();

    return 0;
}

void setIO(string s) {
    (void)!freopen((s + ".in").c_str(), "r", stdin);
    (void)!freopen((s + ".out").c_str(), "w", stdout);
}
accuracy: 1
time_ms: 1650
memory_kb: 11228
final_rank: 20

code_snippet: /*
 *   author : cellul4r
 */
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;
#define all(x) x.begin(), x.end()
const char nl = '\n';
const int N =1e3+1;
const int INF = 1e9+7;
const ll LINF = 1e18+7;

const int dr[] = {-1,0,1,0}, dc[] = {0,1,0,-1};
void setIO(string);
int n,m;
ll a[N], b[N];
ll dp[N][N];
void solve(){
    
    cin>>n>>m;
    while(n != 0 || m != 0) {
        for(int i = 0; i < n; i++) cin>>a[i];
        for(int i = 0; i < n; i++) cin>>b[i];
        for(int i = 0; i < n; i++) {
            a[i] = (b[i] - a[i] + m) % m;
        }

        memset(dp, INF, sizeof dp);
        for(int i = 0; i <= n; i++) {
            dp[0][i] = a[0] + i * m; 
        }
        for(int i = 1; i < n; i++) {
            // x <= y
            // find min prefix of dp[i-1][k]
            // x > y
            // find min suffix of dp[i-1][k]
            vector<ll> pre(n+1), suff(n+1);
            pre[0] = dp[i-1][0];
            for(int k = 1; k <= n; k++) {
                pre[k] = min(pre[k-1], dp[i-1][k] - k * m);
            }

            suff[n] = dp[i-1][n];
            for(int k = n - 1; k >= 0; k--) {
                suff[k] = min(suff[k+1], dp[i-1][k]);
            }

            for(int j = 0; j <= n; j++) {
                //cerr << dp[i-1][j] << " ";
                ll x = a[i] + j * m;
                int l = 0, r = n+1;
                while(l < r) {
                    int mid = l + (r - l) / 2;
                    ll y = a[i-1] + mid * m;
                    if(y >= x) {
                        r = mid;
                    } else {
                        l = mid + 1;
                    }
                }
                if(l <= n) dp[i][j] = min(dp[i][j], suff[l]);
                if(l > 0) dp[i][j] = min(dp[i][j], pre[l-1] + x - a[i-1]);
                /*for(int k = 0; k <= n; k++) {
                    ll y = a[i-1] + k * m;
                    if(x <= y) {
                        dp[i][j] = min(dp[i][j], dp[i-1][k]);
                    } else {
                        dp[i][j] = min(dp[i][j], dp[i-1][k] + x - y);
                    }
                }*/
            }
            //cerr << nl;
        }
        ll ans = LINF;
        for(int i = 0; i <= n; i++) {
            ans = min(ans, dp[n-1][i]);
        }
        cout << ans << nl;
        cin>>n>>m;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;

    //setIO("");
    //cin>>t;
    while(t--)solve();

    return 0;
}

void setIO(string s) {
    (void)!freopen((s + ".in").c_str(), "r", stdin);
    (void)!freopen((s + ".out").c_str(), "w", stdout);
}
accuracy: 1
time_ms: 1650
memory_kb: 11164
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = (ll)4e18;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while (true) {
        int n, m;
        cin >> n >> m;
        if (n == 0 && m == 0) break;

        vector<int> a(n), b(n), d(n);
        for (int i = 0; i < n; i++) cin >> a[i];
        for (int i = 0; i < n; i++) cin >> b[i];
        for (int i = 0; i < n; i++) {
            d[i] = (b[i] - a[i]) % m;
            if (d[i] < 0) d[i] += m;
        }

        int K = n; // safe bound for multiples
        vector<ll> dp_prev(K+1), dp_cur(K+1);

        // base
        for (int k = 0; k <= K; k++) {
            dp_prev[k] = (ll)d[0] + (ll)k * m;
        }

        // DP loop
        for (int i = 1; i < n; i++) {
            // prefix min of dp_prev[j] - j*m
            vector<ll> pref(K+1);
            ll cur = INF;
            for (int j = 0; j <= K; j++) {
                cur = min(cur, dp_prev[j] - (ll)j * m);
                pref[j] = cur;
            }
            // suffix min of dp_prev[j]
            vector<ll> suff(K+2);
            cur = INF;
            for (int j = K; j >= 0; j--) {
                cur = min(cur, dp_prev[j]);
                suff[j] = cur;
            }

            // compute dp_cur
            for (int k = 0; k <= K; k++) {
                ll Ti = (ll)d[i] + (ll)k * m;
                ll numer = Ti - (ll)d[i-1];
                ll j0;
                if (numer <= 0) j0 = 0;
                else j0 = (numer + m - 1) / m; // ceil(numer/m)

                if (j0 < 0) j0 = 0;
                if (j0 > K+1) j0 = K+1;

                ll A = (j0 <= K ? suff[j0] : INF);
                ll B = (j0-1 >= 0 ? pref[j0-1] + (Ti - (ll)d[i-1]) : INF);
                dp_cur[k] = min(A, B);
            }
            dp_prev.swap(dp_cur);
        }

        ll ans = *min_element(dp_prev.begin(), dp_prev.end());
        cout << ans << "\n";
    }
    return 0;
}
accuracy: 1
time_ms: 470
memory_kb: 3460
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e3 + 5;
const int inf = 0x3f3f3f3f;
int n, m;
int a[maxn], dp[maxn][maxn];
int main() {
    while(scanf("%d%d", &n, &m) != EOF) {
        if(n == 0 && m == 0) break;
        for(int i = 0; i < n; ++i) {
            scanf("%d", &a[i]);
        }
        for(int i = 0; i < n; ++i) {
            int x; scanf("%d", &x);
            a[i] = x - a[i];
            if(a[i] < 0) a[i] += m;
            // printf("%d ", a[i]);
        }
        // puts("");
        for(int i = 0; i < n; ++i) {
            dp[0][i] = a[0] + i*m;
        }
        for(int i = 1; i < n; ++i) {
            int dt = a[i] - a[i - 1];
            for(int j = 0; j < n; ++j) {
                if(dt < 0) {
                    dp[i][j] = dp[i - 1][j];
                    if(j > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + m + dt);
                } else {
                    dp[i][j] = dp[i - 1][j] + dt;
                    if(j < n - 1) dp[i][j] = min(dp[i][j], dp[i - 1][j + 1]);
                }
            }
        }
        int ans = inf;
        for(int i = 0; i < n; ++i) {
            ans = min(ans, dp[n - 1][i]);
        }
        printf("%d\n", ans);
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 7428
final_rank: 11

code_snippet: // # pragma GCC target("avx2")
// # pragma GCC optimize("O3")
// # pragma GCC optimize("unroll-loops")
// #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;

// #include<atcoder/modint>
// using namespace atcoder;
// using mint = modint998244353;
// const ll MOD = 998244353;
// // using mint = modint;
// // const ll MOD = 998244353;
// // using mint = modint1000000007;
// // const ll MOD = 1000000007;
// using vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>;

#define rep(i, a, b) for(long long i = (a); i < (b); i++) // [a, b)を昇順に
// #define rep(i, n) for (int i = 0; i < (n); i++)
#define rep2(i, a, b) for (int i = (a); i < (b); i++)
#define drep(i, a, b) for(long long i = (b) - 1; i >= a; i--) // [a, b)を降順に
#define rrep(i, n) for (int i = (n) - 1; i >= 0; i--)
#define all(v) v.begin(), v.end() // 昇順sortに
#define rall(v) v.rbegin(), v.rend() // 降順sortに
#define sz(x) (int)(x).size()
#define decimal(n) cout << fixed << setprecision(n);
#define debug(x) cerr << #x << " = " << x << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define yesno(condition) { if (condition) cout << "Yes" << endl; else cout << "No" << endl; }
using vi = vector<int>; using vvi = vector<vi>; using vs = vector<string>;
using ll = long long; using vl = vector<ll>; using vvl = vector<vl>; using vvvl = vector<vvl>;
using lll = __int128;
using P = pair<ll, ll>; using T = tuple<ll, ll, ll>;
using vc = vector<char>;
const ll MAX = 5'000'009; const ll llINF = 2e18;
const int intINF = 2e9; const long double pi = acos(-1);
const long long INF = 1000000000000000005LL;
ll di[] = {0, -1, 0, 1, -1, -1, 1, 1};
ll dj[] = {1, 0, -1, 0, 1, -1, -1, 1};
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }
template<class T> using pq = priority_queue<T, vector<T>>; //大きい順
template<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>; //小さい順

bool isin(ll i, ll j, ll n, ll m) { return (0 <= i && i < n && 0 <= j && j < m); }
bool is_multiple_overflow(ll a, ll b, ll c) {
  // a * b > cかを判定する
  if (a == 0 || b == 0) return false;
  return (a <= c / b ? false : true);
}

void solve(ll n, ll m) {
  vector<long long> a(n); for(int i = 0; i < n; i++) cin >> a[i]; 
  vector<long long> b(n); for(int i = 0; i < n; i++) cin >> b[i]; 
  vl c(n);
  rep(i, 0, n) {
    if(b[i] >= a[i]) {
      c[i] = b[i] - a[i];
    }
    else c[i] = m + (b[i] - a[i]);
  }

  vl dp(n + 1, llINF);
  rep(k, 0, n + 1) {
    dp[k] = m * k + c[0];
  }

  rep(i, 0, n - 1) {
    vl nextdp(n + 1, llINF);

    vector<P> arr;
    rep(k, 0, n + 1) {
      arr.emplace_back(P({m * k + c[i], dp[k] - (m * k + c[i])}));
    }

    ll curmin = llINF, id = 0;
    rep(k2, 0, n + 1) {
      while(id <= n && arr[id].first <= m * k2 + c[i + 1]) {
        chmin(curmin, arr[id].second);
        id++;
      }
      if(curmin == llINF) continue;

      chmin(nextdp[k2], curmin + m * k2 + c[i + 1]);
    }

    vector<P> arr2;
    rep(k, 0, n + 1) {
      arr2.emplace_back(P({m * k + c[i], dp[k]}));
    }
  
    curmin = llINF, id = n;

    drep(k2, 0, n + 1) {
      while(id >= 0 && arr2[id].first > m * k2 + c[i + 1]) {
        chmin(curmin, arr2[id].second);
        id--;
      }
      if(curmin == llINF) continue;

      chmin(nextdp[k2], curmin);
    }

    swap(nextdp, dp);
  }

  cout << *min_element(all(dp)) << endl;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  while(true) {
    ll n, m;
    cin >> n >> m;
    if(n == 0 && m == 0) return 0;
    solve(n, m);
  }

  return 0;
}
accuracy: 1
time_ms: 660
memory_kb: 3584
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
#if __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;
#endif

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const double pi = 3.141592653589793238;
const int INF = 2147483647;
const ll INFLL = 1LL << 62;
#define all(a) (a).begin(), (a).end()
#define allr(a) (a).rbegin(), (a).rend()
#define rep(i, r, n) for (int i = r; i < (int)n; i++)
#define pb push_back

int n,m;
ll a[1005][1005],ans;
int s[1005],o;

int main()
{
    while(1){
        scanf("%d%d",&n,&m);
        ans=INFLL;
        if(n+m==0){
            return 0;
        }
        for(int i=1;i<=n;++i)
            scanf("%d",&s[i]);
        for(int i=1;i<=n;++i){
            scanf("%d",&o);
            s[i]=o-s[i];
            if(s[i]<0)s[i]+=m;
        }
        for(int i=1;i<=n;++i)
            for(int j=0;j<=n+1;++j)
                a[i][j]=INFLL;
        for(int j=0;j<=n;++j){
            a[1][j]=s[1]+j*m;
            if(n==1)ans=min(ans,a[1][j]);
        }
        for(int i=2;i<=n;++i)
            for(int j=0;j<=n+1;++j){
                if(s[i]>s[i-1])a[i][j]=min(a[i][j],a[i-1][j]+s[i]-s[i-1]);
                if(s[i]<=s[i-1])a[i][j]=min(a[i][j],a[i-1][j]);
                if(j!=0)a[i][j]=min(a[i][j],a[i-1][j-1]+s[i]+m-s[i-1]);
                if(j!=n+1)a[i][j]=min(a[i][j],a[i-1][j+1]);
                if(i==n)ans=min(ans,a[i][j]);
            }
        cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 80
memory_kb: 11408
final_rank: 15

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

bool solve() {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return false;
    vector<int> A(N), B(N);
    for (int i = 0; i < N; i++) cin >> A[i];
    for (int i = 0; i < N; i++) cin >> B[i];
    vector<int> D(N);
    for (int i = 0; i < N; i++) D[i] = B[i] - A[i] + (A[i] > B[i] ? M : 0);
    const long long inf = 1LL << 60;
    vector<long long> dp(N + 1, inf);
    dp[0] = 0;
    for (int i = 0; i < N; i++) {
        vector<long long> ndp(N + 1, inf);
        vector<long long> L(N + 1, inf), R(N + 1, inf);
        for (int j = 0; j <= N; j++) {
            L[j]= dp[j] - j * M - (i ? D[i - 1] : 0);
            if (j > 0) {
                L[j] = min(L[j], L[j - 1]);
            }
        }
        for (int j = N; j >= 0; j--) {
            R[j] = dp[j];
            if (j < N) {
                R[j] = min(R[j], R[j + 1]);
            }
        }
        for (int j = 0, k = 0; j <= N; j++) {
            while (k <= N && k * M + (i ? D[i - 1] : 0) <= j * M + D[i]) k++;
            auto L_val = (k > 0 ? L[k - 1] : inf) + j * M + D[i];
            auto R_val = (k <= N ? R[k] : inf);
            ndp[j] = min(L_val, R_val);
        }
        dp = ndp;
    }
    cout << *min_element(dp.begin(), dp.end()) << '\n';
    return true;
}

int main() {
    while (solve()) {}
}
accuracy: 1
time_ms: 310
memory_kb: 3584
final_rank: 9

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

// #ifndef ONLINE_JUDGE
// #define _GLIBCXX_DEBUG // 配列外参照のエラー
// #endif

// スタンダードライブラリ
#include <bits/stdc++.h>
using namespace std;

// 型関連
using ll = long long;
using lint = long long;
using pll = pair<ll, ll>;
using plll = tuple<ll, ll, ll>;
using pii = pair<int, int>;
using piii = tuple<ll, ll, ll>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vvvi = vector<vector<vector<int>>>;
using vvvvi = vector<vector<vector<vector<int>>>>;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
using vvvl = vector<vector<vector<ll>>>;
using vvvvl = vector<vector<vector<vector<ll>>>>;

template <class T> using prique = priority_queue<T>;

// 型定数
constexpr ll mod = 998244353;
constexpr ll MOD = 1000000007;
int INF32 = 2e9;
ll INF64 = 9e18;
#define endl '\n';

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

/////////////////////////// print関連
template <typename T> void print(vector<T> A);
void print();
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail);
void print(string S);
template <typename T> void print(vector<vector<T>> &F);

inline void Yes(bool f);

///////////////////ここから//////////////////////
bool solve() {
    int N, M;
    cin >> N >> M;
    if (N == 0) {
        return false;
    }
    vi A(N);
    vi B(N);
    for (int i = 0; i < N; i++) {
        cin >> A[i];
    }
    for (int i = 0; i < N; i++) {
        cin >> B[i];
    }
    vi C(N);
    for (int i = 0; i < N; i++) {
        C[i] = (B[i] + M - A[i]) % M;
    }

    vvl dp = vvl(N + 1, vl(N + 1, INF64));
    dp[0][0] = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (dp[i][j] == INF64) {
                continue;
            }
            int pre_hight = j * M;
            if (i > 0) {
                pre_hight += C[i - 1];
            }
            for (int d = -1; d < 2; d++) {
                int nj = j + d;
                if (nj < 0) {
                    continue;
                }
                int hight = C[i] + nj * M;
                dp[i + 1][nj] =
                    min(dp[i + 1][nj], dp[i][j]+ (ll)max(0, hight - pre_hight));
            }
        }
    }
    ll ans = INF64;
    for (int j = 0; j < N + 1; j++) {
        ans=min(ans,dp[N][j]);
    }
    print(ans);

    return true;
}

int main() {
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    while (solve())
        ;
}

////////////////////print/////////////////////////
// 1次元ベクトルを出力する
template <typename T> void print(vector<T> A) {
    if (A.size() == 0) {
        return;
    }
    for (size_t i = 0; i < A.size() - 1; i++) {
        cout << A[i] << ' ';
    }
    cout << A[A.size() - 1] << endl;
    return;
}

// 2次元ベクトルを出力する
template <typename T> void print(vector<vector<T>> &F) {
    for (size_t i = 0; i < F.size(); i++) {
        for (size_t j = 0; j < F[i].size(); j++) {
            cout << F[i][j];
            if (j < F[i].size() - 1) {
                cout << ' ';
            }
        }
        cout << endl;
    }
}

// 空白行を出力するprint
void print() { cout << endl; }

// 数値・文字列を空白区切りで出力する. print(a,b)など
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    cout << head;
    if (sizeof...(tail) != 0)
        cout << " ";
    print(forward<Tail>(tail)...);
}

void print(string S) { cout << S << endl; }

//////////////出力関連

inline void Yes(bool f) {
    if (f) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}
accuracy: 1
time_ms: 150
memory_kb: 11364
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
bool solve();

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

bool solve() {
  int N,M;cin>>N>>M;
  if (N==0) return 0;
  vi A(N),B(N);
  rep(i,0,N)cin>>A[i];
  rep(i,0,N)cin>>B[i];
  
  //カウンタごとの最小押し回数
  vi C(N);
  rep(i,0,N)C[i]=(B[i]-A[i]+M)%M;

  //dp_i = 区間閉じ待ちがc+i*m個ある
  vi dp(N+1,-1);
  rep(i,0,N+1)dp[i]=C[0]+i*M;

  rep(i,1,N){
    vi old(N+1,N*M+1111);
    swap(old,dp);
    
    //なるべく区間を大きくする
    rep(j,0,N+1){
      rep(d,-1,2){
        int pj=j+d;
        if(pj<0||pj>N)continue;
        dp[j]=min(dp[j],old[pj]+max(0,(C[i]+j*M)-(C[i-1]+pj*M)));
      }
    }

  }
  cout<<*min_element(all(dp))<<endl;
  return 1;
}

//O(N^2)な気がするんですけど O(NM)ではなく
accuracy: 1
time_ms: 180
memory_kb: 3712
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
bool solve();

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

bool solve() {
  int N,M;cin>>N>>M;
  if (N==0) return 0;
  vi A(N),B(N);
  rep(i,0,N)cin>>A[i];
  rep(i,0,N)cin>>B[i];
  
  //カウンタごとの最小押し回数
  vi C(N);
  rep(i,0,N)C[i]=(B[i]-A[i]+M)%M;

  //dp_i = 区間閉じ待ちがc+i*m個ある
  vi dp(N+1,-1);
  rep(i,0,N+1)dp[i]=C[0]+i*M;

  rep(i,1,N){
    vi old(N+1,N*M+1111);
    swap(old,dp);
    
    //なるべく区間を大きくする
    rep(j,0,N+1){
      rep(d,-1,2){
        int pj=j+d;
        if(pj<0||pj>N)continue;
        dp[j]=min(dp[j],old[pj]+max(0,(C[i]+j*M)-(C[i-1]+pj*M)));
      }
    }

  }
  cout<<*min_element(all(dp))<<endl;
  return 1;
}
accuracy: 1
time_ms: 180
memory_kb: 3584
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
bool solve();

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

bool solve() {
  int N,M;cin>>N>>M;
  if (N==0) return 0;
  vi A(N),B(N);
  rep(i,0,N)cin>>A[i];
  rep(i,0,N)cin>>B[i];
  
  //カウンタごとの最小押し回数
  vi C(N);
  rep(i,0,N)C[i]=(B[i]-A[i]+M)%M;

  //dp_i = 区間閉じ待ちがc+i*m個ある
  vi dp(N+1,-1);
  rep(i,0,N+1)dp[i]=C[0]+i*M;

  rep(i,1,N){
    vi old(N+1,N*M+1111);
    swap(old,dp);
    
    //なるべく区間を大きくする
    rep(j,0,N+1){
      if(j-1>=0)dp[j]=min(dp[j],old[j-1]+max(0,(C[i]+j*M)-(C[i-1]+(j-1)*M)));
      dp[j]=min(dp[j],old[j]+max(0,(C[i]+j*M)-(C[i-1]+j*M)));
      if(j+1<=N)dp[j]=min(dp[j],old[j+1]);
    }

  }
  cout<<*min_element(all(dp))<<endl;
  return 1;
}
accuracy: 1
time_ms: 80
memory_kb: 3584
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define all(a) (a).begin(), (a).end()
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rrep(i, n) for (int i = (int)(n); i >= 0; i--)
#define range(i, l, r) for (int i = (int)(l); i < (int)(r); i++)
using ll = long long;

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "[";
    for (int i = 0; i < v.size(); i++) {
        os << v[i] << (i == (v.size() - 1) ? "" : ", ");
    }
    os << "]";
    return os;
}

template <typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2> p) {
    os << "{" << p.first << ", " << p.second << "}";
    return os;
}

int main() {
    while (true) {
        int n, m;
        cin >> n >> m;
        if (n == 0) break;

        vector<int> a(n);
        vector<int> b(n);
        rep(i, n) cin >> a[i];
        rep(i, n) cin >> b[i];

        vector<int> c(n + 1);
        rep(i, n) { c[i] = (b[i] - a[i] + m) % m; }
        c[n] = -c[n - 1];
        rrep(i, n - 2) { c[i + 1] = c[i + 1] - c[i]; }

        priority_queue<int> hq{};
        hq.push(-c[0]);
        range(i, 1, n) {
            auto ci = hq.top();
            if (-ci + m < c[i]) {
                hq.pop();
                hq.push(ci - m);
                c[i] -= m;
            }
            hq.push(-c[i]);
        }

        int ans = 0;
        while (!hq.empty()) {
            ans += max(0, -hq.top());
            hq.pop();
        }

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3372
final_rank: 1

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

bool solve() {
  int N, M;
  cin >> N >> M;
  if (N == 0 && M == 0) return false;
  vector<int> A(N), B(N);
  for (int i = 0; i < N; i++) cin >> A[i];
  for (int i = 0; i < N; i++) cin >> B[i];
  vector<int> D(N);
  for (int i = 0; i < N; i++) D[i] = B[i] - A[i] + (A[i] > B[i] ? M : 0);
  const long long inf = 1LL << 60;
  vector<long long> dp(N + 1, inf);
  dp[0] = 0;
  for (int i = 0; i < N; i++) {
    vector<long long> ndp(N + 1, inf);
    vector<long long> L(N + 1, inf), R(N + 1, inf);
    for (int j = 0; j <= N; j++) {
      L[j]= dp[j] - j * M - (i ? D[i - 1] : 0);
      if (j > 0) {
        L[j] = min(L[j], L[j - 1]);
      }
    }
    for (int j = N; j >= 0; j--) {
      R[j] = dp[j];
      if (j < N) {
        R[j] = min(R[j], R[j + 1]);
      }
    }
    for (int j = 0, k = 0; j <= N; j++) {
      while (k <= N && k * M + (i ? D[i - 1] : 0) <= j * M + D[i]) k++;
      auto L_val = (k > 0 ? L[k - 1] : inf) + j * M + D[i];
      auto R_val = (k <= N ? R[k] : inf);
      ndp[j] = min(L_val, R_val);
    }
    dp = ndp;
  }
  cout << *min_element(dp.begin(), dp.end()) << '\n';
  return true;
}

int main() {
  while (solve()) {}
}
accuracy: 1
time_ms: 310
memory_kb: 3712
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define rrep(i,start,end) for (ll i = start;i >= (ll)(end);i--)
#define repn(i,end) for(ll i = 0; i <= (ll)(end); i++)
#define reps(i,start,end) for(ll i = start; i < (ll)(end); i++)
#define repsn(i,start,end) for(ll i = start; i <= (ll)(end); i++)
#define each(p,a) for(auto &p:a)
typedef vector<ll> vll;
typedef vector<pair<ll ,ll>> vpll;
typedef vector<vector<ll>> vvll;
typedef set<ll> sll;
typedef map<ll , ll> mpll;
typedef pair<ll ,ll> pll;
typedef tuple<ll , ll , ll> tpl3;
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)
#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)
#define all(a)  (a).begin(),(a).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
#define sz(x) (ll)x.size()
// << std::fixed << std::setprecision(10)
const ll INF = 1LL << 60;
const ld EPS = 1e-9;
 
inline ll lfloor(ll x,ll m){return (x - ((x % m+ m)%m))/m;}
inline ll positive_mod(ll a,ll m){return (a % m + m)%m;}
inline ll popcnt(ull a){ return __builtin_popcountll(a);}
//0indexed
inline ll topbit(ll a){assert(a != 0);return 63 - __builtin_clzll(a);}
inline ll smlbit(ll a){assert(a != 0);return __builtin_ctzll(a);}
template<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}
template<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}
template<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
template<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
template<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << "{" << p.first << "," << p.second << "}";return os;}
template<class... T>void input(T&... a){(cin >> ... >> a);}
void print(){cout << endl;}
template<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}
template<class T> void pspace(const T& a){ cout << a << ' ';}
void perr(){cerr << endl;}
template<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}
void yes(bool i = true){ return print(i?"yes":"no"); }
void Yes(bool i = true){ return print(i?"Yes":"No"); }
void YES(bool i = true){ return print(i?"YES":"NO"); }
template <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}
template <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}
template <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}
template <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}
//grid探索用
vector<ll> _ta = {0,0,1,-1,1,1,-1,-1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}
	
ll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}
ll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} 
const ll MOD9 = 998244353LL;
const ll MOD10 = 1000000007LL;

void solve(ll n,ll m){
	vll a(n),b(n);cin >> a >> b;
	a--;b--;//mod用
	vector<vector<ll>> dp(n+1,vector<ll>(n+1,INF));// p周で合わせる

	// vvll smldp(n+1,vll(n+1,INF));// 各iについて[0,j]での最小
	vvll bigdp(n+1,vll(n+1,INF));//各iについて[j,n]での最小
	dp[0][0] = 0;
	// repn(i,n){
	// 	smldp[0][i] = 0;
	// }
	vll base(n);
	rep(i,n){
		if(a[i] <= b[i]){
			base[i] = b[i] - a[i];
		}else{
			base[i] = b[i] - a[i] + m;
		}
	}

	rep(i,n){
		ll last = INF;
		repn(j,n){// j周で
			ll num = m * j +base[i];
			if(num < 0){
				last += m;
				chmin(last,dp[i][j]);
				continue;
			}
			//j周より大から
			if(j != n){
				chmin(dp[i+1][j],bigdp[i][j+1]);
			}
			//ちょうどj周で
			if(i == 0 ){
				chmin(dp[i+1][j],dp[i][j] + num);
			}else if(m * j + base[i-1] < num){
				chmin(dp[i+1][j],dp[i][j]+num - (m * j + base[i-1]));
			}else{
				chmin(dp[i+1][j],dp[i][j]);
			}
			//j周未満から
			if(j != 0 && i != 0){
				chmin(dp[i+1][j],last+num - (m * (j-1) + base[i-1]));
			}else if(j != 0){
				chmin(dp[i+1][j],last+num);
			}
			last += m;
			chmin(last,dp[i][j]);
		}
		//bigの更新
		rrep(j,n,0){
			if(j == n){
				bigdp[i+1][n] = dp[i+1][n];
			}else{
				bigdp[i+1][j] = min(dp[i+1][j],bigdp[i+1][j+1]);
			}
		}

	}
	cout << *min_element(all(dp[n])) << endl;

}
 
int main(){
	ios::sync_with_stdio(false);cin.tie(nullptr);
	while(true){
		LL(n,m);
		if(n == 0 && m == 0)break;
		solve(n,m);
	}
}
accuracy: 1
time_ms: 350
memory_kb: 19200
final_rank: 18

code_snippet: #include "bits/stdc++.h"
using namespace std;

#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define FOR(i, m, n) for (ll i = m; i < n; i++)
#define FORR(i, m, n) for (ll i = m; i >= n; i--)
#define REPO(i, n) for (ll i = 1; i <= n; i++)
#define ll long long
#define INF (ll)1ll << 60
#define MINF (-1 * INF)
#define ALL(n) n.begin(), n.end()
#define MOD (ll)998244353
#define P pair<ll, ll>


int main(){
    while(1){
        ll n, m;
        cin >> n >> m;
        if(n == 0 and m == 0){
            return 0;
        }
        vector<ll> a(n) , b(n);
        vector<vector<ll>> dp(n + 1, vector<ll>(n + 2, INF));
        REP(i, n)cin >> a[i];
        REP(i, n) cin >> b[i];
        dp[0][0] = 0;
        REP(i, n){
            if(a[i] > b[i]) b[i] += m;
            //if(i == 0){
            if(i == 0){
                dp[i + 1][0] = min({dp[i + 1][0], dp[i][0] + b[i] - a[i]});
                continue;
            }
            REP(j, n + 1){
                ll now = b[i] - a[i];
                ll bf = -1;
                //else {
                    bf = b[i - 1] - a[i - 1];
                    dp[i + 1][j] = min({dp[i + 1][j], dp[i][j] + max(now + m * (j) - (bf + m * j), 0ll)});
                    if(j + 1 < n + 2)dp[i + 1][j + 1] = min({dp[i + 1][j + 1], dp[i][j] + max(now + m * (j + 1) - (bf + m * j), 0ll)});
                    if(j - 1 >= 0) dp[i + 1][j - 1] =min({dp[i + 1][j - 1], dp[i][j] + max(now + m * (j - 1) - (bf + m * j), 0ll)});
                //}
            //}
                //cout << i <<" " << j <<" " << dp[i][j] << endl;
            }
        }
        ll ans  = INF;
        REP(i, n + 2){
            ans = min(ans , dp[n][i]);
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 260
memory_kb: 10940
final_rank: 17

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

#define rep(i,l,r) for(int i=(l);i<(r);i++)
#define all(v) begin(v),end(v)
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
int main(){
  int N,M;
  while(1){
    cin>>N>>M;
    if(N==0&&M==0)return 0;
    vi A(N),B(N);
    for(int &i:A)cin>>i;
    for(int &i:B)cin>>i;
    rep(i,0,N){
      B[i]-=A[i];
      if(B[i]<0)B[i]+=M;
    }
    vl dp(N+1);
    rep(i,0,N+1){
      dp[i]=B[0]+i*M;
    }
    // rep(i,0,N+1)cerr<<`
    rep(i,1,N){
      vl ndp(N+1,1e18);
      ll m=1e18;
      if(B[i]>B[i-1]){
        int t=B[i]-B[i-1];
        rep(ri,0,N+1){
          int j=N-ri;
          ndp[j]=min(ndp[j],m);
          ndp[j]=min(ndp[j],dp[j]+t);
          m=min(m,dp[j]);
        }
      }else{
        int t=B[i]-B[i-1]+M;
        rep(ri,0,N+1){
          int j=N-ri;
          m=min(m,dp[j]);
          ndp[j]=min(ndp[j],m);
          if(j-1>=0)ndp[j]=min(ndp[j],dp[j-1]+t);
        }
      }
      ndp[0]=min(ndp[0],m+B[i]);
      rep(j,0,N){
        ndp[j+1]=min(ndp[j+1],ndp[j]+M);
      }
      rep(i,0,N+1)dp[i]=ndp[i];
      // rep(i,0,N+1)cerr<<dp[i]<<' ';
      // cerr<<endl;
    }
    cout<<*min_element(all(dp))<<'\n';
  }
}
accuracy: 1
time_ms: 100
memory_kb: 3456
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for(ll i = a; i < (b); i++)
#define all(a) (a).begin(), (a).end()

int main(){
    while(true){
        ll n,m;
        cin>>n>>m;
        if(n==0)break;
        vector<ll> a(n);
        vector<ll> b(n);
        vector<ll> c={0};
        rep(i,0,n){
            cin>>a[i];
        }
        rep(i,0,n){
            cin>>b[i];
        }
        rep(i,0,n){
            c.push_back((b[i]-a[i]+m)%m);
        }
        vector<ll> z(1100,2000000000000000000);
        z[0]=0;
        rep(i,0,n){
            ll d=(c[i+1]-c[i]+m)%m;
            vector<ll> nz(1100,2000000000000000000);
            rep(j,0,1050){
                if(c[i+1]>=c[i]){
                    nz[j]=min(nz[j],z[j]+d);
                    if(j!=0)nz[j-1]=min(nz[j-1],z[j]);
                }
                else{
                    nz[j+1]=min(nz[j+1],z[j]+d);
                    nz[j]=min(nz[j],z[j]);
                }
            }
            z=nz;
        }
        ll ans=1000000000000000000;
        rep(i,0,1100){
            ans=min(ans,z[i]);
        }
        cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 80
memory_kb: 3584
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;

#define rep(i,n) for(ll i=0;i<n;++i)
#define all(a) (a).begin(),(a).end()
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
template<class T> T div_floor(T a, T b) { return a / b - ((a ^ b) < 0 && a % b); }
template<class T> T div_ceil(T a, T b) { return a / b + ((a ^ b) > 0 && a % b); }
template <typename T, typename U> inline bool chmin(T &x, U y) { return (y < x) ? (x = y, true) : false; }
template <typename T, typename U> inline bool chmax(T &x, U y) { return (x < y) ? (x = y, true) : false; }


void solve(ll N,ll M) {
    vector<ll> A(N);
    vector<ll> B(N);
    rep(i,N){
        cin>>A[i];
    }
    rep(i,N){
        cin>>B[i];
    }
    vector<ll> C(N);
    rep(i,N){
        ll r=B[i]-A[i];
        r%=M;
        r+=M;
        r%=M;
        C[i]=r;
    }
    vector<ll> dp(N+1,1e9);
    dp[0]=0;
    ll bef=0;
    rep(i,N){
        ll nxt=C[i];
        vector<ll> ndp(N+1,1e9);
        rep(j,N+1){
            if (j>0){
                chmin(ndp[j-1],dp[j]+abs((j*M+bef)-((j-1)*M+nxt)));
            }
            if (true){
                chmin(ndp[j],dp[j]+abs((j*M+bef)-(j*M+nxt)));
            }
            if (j<N){
                chmin(ndp[j+1],dp[j]+abs((j*M+bef)-((j+1)*M+nxt)));
            }
        }
        swap(dp,ndp);
        bef=nxt;
    }
    ll ans=1e9;
    rep(i,N+1){
        chmin(ans,dp[i]+abs(i*M+bef));
    }
    ans/=2;
    cout<<ans<<endl;
    return;
}


int main() {
    ll N,M;
    while (true){
        cin>>N>>M;
        if (N==0){
            break;
        }
        solve(N,M);
    }
    return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 3712
final_rank: 3

code_snippet: // AOJ #1635
// Tally Counters 2025.2.13

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

int n, m;

static unsigned dp[1010][1010];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    while (true) {
        cin >> n >> m;
        if (n == 0) break;

        vector<int> A(n), B(n);
        for (int i = 0; i < n; ++i) cin >> A[i];
        for (int i = 0; i < n; ++i) {
            cin >> B[i];
            A[i] = (B[i] - A[i] + m) % m;
        }

        memset(dp, 0xFF, sizeof(dp));

        for (int j = 0; j < n; ++j) 
            dp[0][j] = A[0] + (unsigned)j * (unsigned)m;

        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                {
                    unsigned cost = (unsigned)std::max(0, A[i] - A[i - 1]);
                    if (dp[i - 1][j] != 0xFFFFFFFF) {
                        unsigned val = dp[i - 1][j] + cost;
                        dp[i][j] = std::min(dp[i][j], val);
                    }
                }
                {
                    if (j > 0 && dp[i - 1][j - 1] != 0xFFFFFFFF) {
                        unsigned cost = (unsigned)A[i] + (unsigned)(m - A[i - 1]);
                        unsigned val = dp[i - 1][j - 1] + cost;
                        dp[i][j] = min(dp[i][j], val);
                    }
                }
                {
                    if (j + 1 < n && dp[i - 1][j + 1] != 0xFFFFFFFF) {
                        dp[i][j] = min(dp[i][j], dp[i - 1][j + 1]);
                    }
                }
            }
        }
        int best = INT_MAX;
        for (int j = 0; j < n; ++j) {
            if (dp[n - 1][j] < 0xFFFFFFFF) {
                best = min(best, (int)dp[n - 1][j]);
            }
        }
        cout << best << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 7392
final_rank: 13

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

void chmax(int &a, int b){
    if(a<b)a=b;
}

int main(){
    while(1){
        int n,m;
        cin>>n>>m;
        if(n==0){
            return 0;
        }
        vector<int> a(n);
        vector<int> b(n);
        for(int i=0;i<n;i++)cin>>a[i];
        for(int i=0;i<n;i++)cin>>b[i];
        for(int i=0;i<n;i++){
            if(a[i]>b[i])a[i]=m+b[i]-a[i];
            else a[i]=b[i]-a[i];
        }
        vector<int> d(n);
        vector<int> rwa(n+1);
        d[0] = a[0];
        for(int i=1;i<n;i++){d[i]=a[i]-a[i-1]; if(d[i]<0)d[i]+=m;}
        for(int i=1;i<=n;i++)rwa[i]=rwa[i-1]+d[i-1];
        //二乗が通る！！
       priority_queue<int> pq;
       int ans=0;
       int now=0;
       for(int i=0;i<n;i++){
        if(i==0){ans+=d[0];now=ans;}
        else{
            int neg = m-d[i];
            if(neg==m)neg=0;
            pq.push(neg);
            now-=neg;
            if(now<0){
                int v = pq.top();
                if(v==0)v=m;
                else v=m-v;
                now+=m;
                ans+=v;
                pq.pop();
            }
        }
       }
       cout<<ans<<endl;

        
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3492
final_rank: 2