guruguru
6576: guruguru
时间限制: 1 Sec 内存限制: 128 MB提交: 60 解决: 28
[提交] [状态] [命题人: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.
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
n m
a1 a2 … an
输出
Print the minimum number of times Snuke needs to press the buttons.
样例输入
4 6
1 5 1 4
样例输出
5
#include <bits/stdc++.h> #include<map> #include<set> using namespace std; const int maxn=1e6; typedef long long ll; int n,m; ll p[maxn],psum[maxn],tot,ans; int main() { cin>>n>>m; for(int i=1;i<=n;i++){ scanf("%lld",&p[i]); } for(int i=2;i<=n;i++){ ll l=p[i-1],r=p[i]; if(r<l)r+=m; tot+=r-l; if(r-l>=2){ psum[l+2]+=1,psum[r+1]-=r-(l+2)+1+1,psum[r+2]+=r-(l+2)+1; } } for(int i=1;i<=2*m;i++)psum[i]+=psum[i-1]; for(int i=1;i<=2*m;i++)psum[i]+=psum[i-1]; for(int i=1;i<=m;i++)ans=max(ans,psum[i]+psum[i+m]); cout<<tot-ans<<endl; return 0; }