题意:
数据范围:1<=n,m<=3e5,0<=a(i)<m
解法:
x次操作能做到,那么x+1次一定也能做到,满足单调性。
那么二分操作次数,贪心地进行check即可。 check:每个数最多进行mid次操作,贪心地让左边的数尽量小,判断能否令序列满足不下降即可。
code:
#include<bits/stdc++.h>
using namespace std
;
#define int long long
const int maxm
=3e5+5;
int a
[maxm
];
int n
,m
;
bool check(int mid
){
int last
=-1;
if(a
[1]+mid
>=m
)last
=0;
else last
=a
[1];
for(int i
=2;i
<=n
;i
++){
if(a
[i
]==last
)continue;
else if(a
[i
]>last
){
if(a
[i
]+mid
>=m
&&(a
[i
]+mid
)%m
>=last
){
continue;
}else{
last
=a
[i
];
}
}else if(a
[i
]<last
){
if(a
[i
]+mid
>=last
){
continue;
}else{
return 0;
}
}
}
return 1;
}
signed main(){
cin
>>n
>>m
;
for(int i
=1;i
<=n
;i
++){
cin
>>a
[i
];
}
int ans
=-1;
int l
=0,r
=m
;
while(l
<=r
){
int mid
=(l
+r
)/2;
if(check(mid
))ans
=mid
,r
=mid
-1;
else l
=mid
+1;
}
cout
<<ans
<<endl
;
return 0;
}