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

4 篇文章 0 订阅

题目链接

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值