Codeforces Round #562 (Div. 2)——C. Increasing by Modulo

122 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情

Codeforces Round #562 (Div. 2)——C. Increasing by Modulo

Problem - C - Codeforces

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 kk and kk indices i1,i2,…,ik such that 1≤i1<i2<…<ik≤n. He should then change aij to ((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 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 nn and mm (1≤n,m≤300000) — the number of integers in the array and the parameter mm.

The next line contains nn 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

input

5 7
0 6 1 3 2

output

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.

问题解析

题目意思是,给你一个数组和一个数m,每次操作你可以选任意个数,把他们从ai变成(ai+1)%m,问要让数组变成单调不减,需要至少几次操作。

可以想出,如果使用cnt次操作可以满足条件,那么cnt+1次操作肯定也能做到,而cnt-1次操作不一定能做到。满足单调性,可以尝试二分答案。

想象一下,二分答案的下限就是0,即一次不操作就满足条件,上限为m,因为不管数组什么情况,一定可以用m次操作把数组全变成同一个数,全变成一个数也是满足条件的。

每次check,把每个数变的尽量小,如果变不了,就看当前数是否大于小于上一个数,如果不满足,说明没法在当前次数内把数组变成单调不减,返回false。如果过程中没返回false,则说明可以在当前次数内把数组变成单调不减,返回true。

AC代码

int n, m;
int a[N];
bool check(int mid)
{
    int ans = 0;
    for (int i = 1; i <= n; i++)
    {
        int tmp = (ans - a[i] + m) % m;
        if (tmp > mid)
        {
            if (a[i] >= ans)ans = a[i];
            else return false;
        }
    }
    return true;
}
void solve() 
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)cin >> a[i];
    int l = 0, r = m;
    while (l < r)
    {
        int mid = (l + r) / 2;
        if (check(mid))r = mid;
        else l = mid + 1;
    }
    cout << l;
}