guruguru 前缀和

6576: guruguru

时间限制: 1 Sec  内存限制: 128 MB
提交: 32  解决: 13
[提交] [状态] [讨论版] [命题人:admin]

题目描述

Snuke is buying a lamp. The light of the lamp can be adjusted to m levels of brightness, represented by integers from 1 through m, by the two buttons on the remote control.
The first button is a "forward" button. When this button is pressed, the brightness level is increased by 1, except when the brightness level is m, in which case the brightness level becomes 1.
The second button is a "favorite" button. When this button is pressed, the brightness level becomes the favorite brightness level x, which is set when the lamp is purchased.
Snuke is thinking of setting the favorite brightness level x so that he can efficiently adjust the brightness. He is planning to change the brightness n−1 times. In the i-th change, the brightness level is changed from ai to ai+1. The initial brightness level is a1. Find the number of times Snuke needs to press the buttons when x is set to minimize this number.

Constraints
2≤n,m≤105
1≤ai≤m
ai≠ai+1
n, m and ai are integers.

 

 

输入

Input is given from Standard Input in the following format:
n m
a1 a2 … an

 

输出

Print the minimum number of times Snuke needs to press the buttons.

 

样例输入

4 6
1 5 1 4

 

样例输出

5

用一个数组记录当a[i]为x时,其他数可以减少的步数

利用前缀和思想,将l+2,r+1,r+2分别加减值,然后进行两次前缀和相加,最后找出最大的可以减少的步数

#include <bits/stdc++.h>
using namespace std;
const  int maxx=1e5+100;
const int INF=99999999;
const int MOD=1e9+7;
typedef long long ll;
int a[maxx];
ll p[maxx*2];
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=0; i<n; i++){
        cin>>a[i];
    }
    ll ans=0;
    for(int i=1; i<n; i++){
        int l=a[i-1],r=a[i];
        if(r-l<0)  r+=m;
        ans+=r-l;
        if(r-l>1){
            p[l+2] += 1;
            p[r+1] -= (r-(l+2)+1)+1;
            p[r+2] += (r-(l+2)+1);
        }
    }
    for(int i=1; i<=2*m; i++)  p[i] += p[i-1];
    for(int i=1; i<=2*m; i++)  p[i] += p[i-1];
    ll b=-1;
    for(int i=1; i<=m; i++)
        b=max(b,p[i]+p[i+m]);
    cout<<ans-b<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/renxiaomiao/p/9642685.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值