Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define X first
- #define Y second
- using namespace std;
- typedef long long ll;
- typedef pair<int, int> pii;
- const int N = 3e5 + 7;
- pair<ll, ll> bit[N];
- int n, l, r, b[N], m;
- pii a[N];
- ll sum , res = LLONG_MAX, f[N];
- void upd(int p, ll x, ll y, int n)
- {
- while (p<=n)
- {
- bit[p].X+=x;
- bit[p].Y+=y;
- p+=(p&(-p));
- }
- }
- pair<ll, ll> Get(int p)
- {
- ll res = 0, dem = 0;
- while (p>0)
- {
- res+=bit[p].X;
- dem+=bit[p].Y;
- p-=(p&(-p));
- }
- return make_pair(res,dem);
- }
- int main()
- {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- cin>>n>>m;
- for (int i=1; i<=n; i++) cin>>b[i];
- for (int i=1; i<n; i++)
- if (b[i]<b[i+1]) a[i] = make_pair(b[i],b[i+1]); else a[i] = make_pair(b[i],b[i+1] + m);
- n--;
- sort(a+1, a + 1 + n);
- for (int i=1; i<=n; i++) sum = sum + a[i].Y - a[i].X;
- int j = 0;
- for (int x = 1; x<=m; x++)
- {
- while (j<n && a[j+1].X<x)
- {
- j++;
- upd(a[j].Y, a[j].X, 1, 2*m);
- }
- pair<ll, ll> t = Get(2*m), q = Get(x-1);
- ll cnt = t.Y - q.Y;
- ll sum1 = t.X- q.X;
- ll tmp = sum + sum1 - 1LL*cnt*x + cnt;
- f[x] = tmp;
- }
- for (int i=1; i<=2*m; i++) bit[i] = make_pair(0,0);
- j = 0;
- for (int x = 1; x<=m; x++)
- {
- while (j<n && a[j+1].X<x+m)
- {
- j++;
- upd(a[j].Y, a[j].X, 1, 2*m);
- }
- pair<ll, ll> t = Get(2*m), q = Get(x+m-1);
- ll cnt = t.Y - q.Y;
- ll sum1 = t.X- q.X;
- ll tmp = f[x] + sum1 - 1LL*cnt*(x+m) + cnt;
- f[x] = tmp;
- res = min(res,f[x]);
- }
- cout<<res;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment