题目链接
http://arc077.contest.atcoder.jp/tasks/arc077_c
题目大意
有一个m级调光的灯,他有两个键,一个可以使亮度+1, 一个可以使灯到指定亮度, 如果亮度为m时再按第一个键,亮度会变为1
给你n个亮度,问你从亮度1开始模拟n个亮度最小按键次数是多少
思路
设cnt[i]表示第二个键设在i位置能比按第一个键节省的按键次数
设l = op[i], r = op[i+1], 如果l>r, 令r = r+m, 这样就不用考虑上界的问题了
那么对于每一对l, r, 如果r-l<=1, 那么无论x在什么位置, 第二个按钮都不能减少操作次数
如果r-l>1, 那么 x在l+2位置使用第二个按钮能够减少1次操作, 在l+3位置能减少2次… 在r位置能够减少r-(l+2)+1次操作
所以cnt[l+2] += 1, cnt[l+3] += 2 … cnt[r] += r-(l+2)+1
对每一对l, r如此处理, 得到最后的cnt数组
设totl为只使用第一个按钮所需要的操作总次数
那么最少操作次数 = totl - max{cnt[i]+cnt[i+m]}, 1<=i<=m
优化
如果对每一对l, r都作上述处理,那复杂度就是o(m*n)
如果要将cnt[l]到cnt[r]依次加上1, 2, … r-l+1
我们可以标记一下这三个值:cnt[i] += 1, cnt[r+1] -= r-l+1 + 1, cnt[r+2] += r-l+1, 每次只更新这三个值, 最后再从头到尾cnt[i] += cnt[i-1]就行了
这样复杂度就变成o(m+n)了
关于差分标记可以看一下这篇博客
http://blog.csdn.net/qq_36378681/article/details/74414977
代码
#include<bits/stdc++.h>
using namespace std;
const int M = 3e5 + 10;
long long cnt[M];
int op[M];
int main()
{
memset(cnt, 0, sizeof(cnt));
int n, m;
long long totl = 0;
scanf("%d%d", &n, &m);
for(int i=0; i<n; ++i)
scanf("%d", op + i);
for(int i=1; i<n; ++i) {
int l = op[i-1], r = op[i];
if(l > r) r += m;
totl += r - l;
if(r - l > 1) {
++cnt[l+2];
cnt[r+1]-=(r-(l+2) +1)+1;
cnt[r+2]+=(r-(l+2)+1);
}
}
for(int i=1; i<=2*m; ++i) {
cnt[i] += cnt[i-1];
}
for(int i=1; i<=2*m; ++i) {
cnt[i] += cnt[i-1];
}
long long ans = -1;
for(int i=1; i<=m; ++i) {
ans = max(cnt[i] + cnt[i+m], ans);
}
cout<<totl - ans<<endl;
return 0;
}
参考自某大佬博客http://blog.csdn.net/litmxs/article/details/74276105