咕噜噜。
容易发现每个设定值对每段区间的贡献为
f(s, t, xi) = xi - (s+1)
f(s, t, xi+1) = xi+1 - (s+1)
(s < xi <= t)
类似树状数组维护区间修改,用两个区间分别维护xi的前缀和以及(s+1)的前缀和。
代码:
#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const double PI = acos(-1.0);
const double eps = 1e-10;
int dcmp(double x) { if(fabs(x) < eps) return 0; else return x<0?-1:1; }
const int N = 1e5+5;
const ll MOD = 1e9+7;
int a[N];
ll s1[2*N], s2[2*N];
int main() {
memset(s1, 0, sizeof(s1));
memset(s2, 0, sizeof(s2));
int n, m, l, r;
ll ans = 0;
scanf("%d%d%d", &n, &m, &l);
for(int i = 1; i < n; i++) {
scanf("%d", &r);
if(l > r) r += m;
ans += r-l;
s1[l+1]++, s1[r+1]--;
s2[l+1] += l+1, s2[r+1] -= l+1;
l = r%m;
}
for(int i = 1; i <= 2*m; i++) s1[i] += s1[i-1], s2[i] += s2[i-1];
ll maxa = 0;
for(int i = 1; i <= m; i++) {
ll tmp = s1[i]*(ll)i-s2[i]+s1[i+m]*(ll)(i+m)-s2[i+m];
maxa = max(tmp, maxa);
}
printf("%lld\n", ans-maxa);
return 0;
}