题目链接:点击这里
题目大意:
给出
n
,
m
n,m
n,m 和一个长度为
n
n
n 的序列
a
1
,
a
2
,
.
.
.
,
a
n
a_1,a_2,...,a_n
a1,a2,...,an
每次操作可以选择一个数
k
k
k 和
k
k
k 个数
b
1
,
b
2
,
.
.
.
,
b
k
b_1,b_2,...,b_k
b1,b2,...,bk ,使得
a
b
i
=
(
a
b
i
+
1
)
m
o
d
m
a_{b_i}=(a_{b_i}+1) \mod m
abi=(abi+1)modm ,求使序列
a
a
a 单调不下降的最小操作次数
题目分析:
最小操作次数显然满足答案的单调性,我们考虑二分答案的
c
h
e
c
k
check
check 如何写:我们对相邻元素
a
[
i
]
,
a
[
i
−
1
]
a[i],a[i-1]
a[i],a[i−1] 的大小关系分三种情况讨论:
- a [ i ] = a [ i − 1 ] a[i]=a[i-1] a[i]=a[i−1] 此时让 a [ i ] a[i] a[i] 保持不变即可
- a [ i ] > a [ i − 1 ] a[i]>a[i-1] a[i]>a[i−1] 如果能让 a [ i ] a[i] a[i] 通过循环变成 a [ i − 1 ] a[i-1] a[i−1] 更好,此时需要操作次数为 a [ i − 1 ] + m − a [ i ] a[i-1]+m-a[i] a[i−1]+m−a[i] ,如果操作次数不够就维持原样即可
- a [ i ] < a [ i − 1 ] a[i]<a[i-1] a[i]<a[i−1] 此时我们需要让 a [ i ] a[i] a[i] 增加到 a [ i − 1 ] a[i-1] a[i−1] 使之保持序列的单调不下降,需要的操作次数为 a [ i − 1 ] − a [ i ] a[i-1]-a[i] a[i−1]−a[i]
具体细节见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
ll read()
{
ll res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 5e5+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
ll n,m,a[maxn],tmp[maxn];
bool check(int val)
{
memcpy(tmp,a,sizeof(a));
for(int i = 1;i <= n;i++)
if(tmp[i] < tmp[i-1])
{
if(tmp[i-1]-tmp[i] > val) return false;
tmp[i] = tmp[i-1];
}
else if(tmp[i-1]+m-tmp[i] <= val) tmp[i] = tmp[i-1];
return true;
}
int main()
{
n = read(),m = read();
for(int i = 1;i <= n;i++)
a[i] = read();
int l = 0,r = m,ans = m;
while(l <= r)
{
int mid = l+r>>1;
if(check(mid))
{
ans = min(ans,mid);
r = mid-1;
}
else l = mid+1;
}
printf("%d\n",ans);
return 0;
}