Guest User

Untitled

a guest
Nov 3rd, 2021
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define X first
  3. #define Y second
  4.  
  5. using namespace std;
  6. typedef long long ll;
  7. typedef pair<int, int> pii;
  8. const int N = 3e5 + 7;
  9. pair<ll, ll> bit[N];
  10. int n, l, r, b[N], m;
  11. pii a[N];
  12. ll sum , res = LLONG_MAX, f[N];
  13. void upd(int p, ll x, ll y, int n)
  14. {
  15.     while (p<=n)
  16.     {
  17.         bit[p].X+=x;
  18.         bit[p].Y+=y;
  19.         p+=(p&(-p));
  20.     }
  21. }
  22. pair<ll, ll> Get(int p)
  23. {
  24.     ll res = 0, dem = 0;
  25.     while (p>0)
  26.     {
  27.         res+=bit[p].X;
  28.         dem+=bit[p].Y;
  29.         p-=(p&(-p));
  30.     }
  31.     return make_pair(res,dem);
  32. }
  33. int main()
  34. {
  35.    
  36.     ios_base::sync_with_stdio(0);
  37.     cin.tie(0);
  38.     cout.tie(0);
  39.     cin>>n>>m;
  40.     for (int i=1; i<=n; i++) cin>>b[i];
  41.     for (int i=1; i<n; i++)
  42.         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);
  43.     n--;
  44.     sort(a+1,  a + 1  + n);
  45.     for (int i=1; i<=n; i++) sum = sum + a[i].Y - a[i].X;
  46.     int j = 0;
  47.     for (int x = 1; x<=m; x++)
  48.     {
  49.         while (j<n && a[j+1].X<x)
  50.         {
  51.             j++;
  52.             upd(a[j].Y, a[j].X, 1, 2*m);
  53.         }
  54.         pair<ll, ll> t = Get(2*m), q = Get(x-1);
  55.         ll cnt = t.Y - q.Y;
  56.         ll sum1 = t.X- q.X;
  57.         ll tmp = sum + sum1 - 1LL*cnt*x + cnt;
  58.         f[x] = tmp;
  59.     }
  60.     for (int i=1; i<=2*m; i++) bit[i] = make_pair(0,0);
  61.     j = 0;
  62.     for (int x = 1; x<=m; x++)
  63.     {
  64.         while (j<n && a[j+1].X<x+m)
  65.         {
  66.             j++;
  67.             upd(a[j].Y, a[j].X, 1, 2*m);
  68.         }
  69.         pair<ll, ll> t = Get(2*m), q = Get(x+m-1);
  70.         ll cnt = t.Y - q.Y;
  71.         ll sum1 = t.X- q.X;
  72.         ll tmp = f[x] + sum1 - 1LL*cnt*(x+m) + cnt;
  73.         f[x] = tmp;
  74.         res = min(res,f[x]);
  75.     }
  76.     cout<<res;
  77.     return 0;
  78. }
  79.    
Advertisement
Add Comment
Please, Sign In to add comment