time limit per test
2.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Toad Zitz has an array of integers, each integer is between 00 and m−1m−1 inclusive. The integers are a1,a2,…,ana1,a2,…,an.
In one operation Zitz can choose an integer kk and kk indices i1,i2,…,iki1,i2,…,ik such that 1≤i1<i2<…<ik≤n1≤i1<i2<…<ik≤n. He should then change aijaij to ((aij+1)modm)((aij+1)modm) for each chosen integer ijij. The integer mm is fixed for all operations and indices.
Here xmodyxmody denotes the remainder of the division of xx by yy.
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 nn and mm (1≤n,m≤3000001≤n,m≤300000) — the number of integers in the array and the parameter mm.
The next line contains nn space-separated integers a1,a2,…,ana1,a2,…,an (0≤ai<m0≤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 00.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
input
Copy
5 3
0 0 0 1 2
output
Copy
0
input
Copy
5 7
0 6 1 3 2
output
Copy
1
Note
In the first example, the array is already non-decreasing, so the answer is 00.
In the second example, you can choose k=2k=2, i1=2i1=2, i2=5i2=5, the array becomes [0,0,1,3,3][0,0,1,3,3]. It is non-decreasing, so the answer is 11.
#include <bits/stdc++.h>
using namespace std;
int n,m,a[300005];
bool f(int x)
{
int p=0;
for (int i=0; i<n; i++)
{
if ((m+p-a[i])%m > x)
{
if (a[i] < p)
return false;
p = a[i];
}
}
return true;
}
int main()
{
scanf("%d %d",&n,&m);
for (int i=0; i<n; i++)
scanf("%d",a+i);
int lo=0,hi=m-1;
while (lo<hi)
{
int k=(lo+hi)/2;
if (f(k))
hi=k;
else
{
lo=k+1;
}
}
printf("%d\n",lo);
return 0;
}