Toad Zitz has an array of integers, each integer is between 0 and m−1 inclusive. The integers are a1,a2,…,an.
In one operation Zitz can choose an integer k and k indices i1,i2,…,ik such that 1≤i1<i2<…<ik≤n. He should then change aij to ((aij+1)modm) for each chosen integer ij. The integer m is fixed for all operations and indices.
Here xmody denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1≤n,m≤300000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a1,a2,…,an (0≤ai<m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
inputCopy
5 3
0 0 0 1 2
outputCopy
0
inputCopy
5 7
0 6 1 3 2
outputCopy
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i1=2, i2=5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
題意: 有n個數,每個數ai均小於m,有一項操作,選一個正整數k,有k個數,i1,i2…ik,表示索引,即n個數中第ij個數,將該數(aij+1)%m,使得得到的序列遞增(非嚴格遞增)。最少的操作次數。
思路: 二分操作次數,對於操作次數x,將當前數ai與前個數pre進行比較,因爲要求最少的操作次數,使得ai到大pre時達到最小,即:當ai小於pre時,ai+x == pre,或者當ai+x>=m&&(ai+x)%m ==pre時,可以達到最小。若ai+x<pre,即當前不能到達。其他情況更新pre。
#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[310000];
bool solve(int x)
{
int pre=0;
for(int i=0;i<n;i++){
if(a[i]+x<pre) return false;//當前情況不能到達
if(a[i]<=pre||(a[i]+x>=m&&(a[i]+x)%m>=pre)) continue;
//a[i]<=pre 當ai小於pre時,ai+x 能到達 pre,
//(a[i]+x>=m&&(a[i]+x)%m>=pre) 當ai+x>=m&&(ai+x)%m 能到達pre時
else pre=a[i];
}
return true;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
int l=0,r=m;
int ans;
while(l<=r){
int mid = (l+r)>>1;
if(solve(mid)){
r = mid-1;
ans = mid;
}
else l = mid+1;
}
cout<<ans<<endl;
return 0;
}