[CodeForces1000]B. Light It Up
一道贪心的简单题,插入无非就是两种情况:
- 在开灯的区间内插入,应该让插入的元素尽可能地靠后
- 在关灯的区间内插入,应该让插入的元素尽可能地靠前
注意:
g1
和g2
的含义,g1
是指不落单(最后两次操作刚好完成一次开关)的后缀和,而g2
则指的是会落单的后缀和i+1
和i+2
的选择,应该在纸上画图而不是凭空乱想- 因为
n
的奇偶性不知道,所以ans
的初始值为末尾两个数的最大值
B. Light It Up
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment
The lamp allows only good programs. Good program can be represented as a non-empty array
The lamp follows program
Since you are not among those people who read instructions, and you don’t understand the language it’s written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program
Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from
Input
First line contains two space separated integers
Second line contains
Output
Print the only integer — maximum possible total time when the lamp is lit.
Examples
input
3 104 6 7
output
8
input
2 121 10
output
9
input
2 73 4
output
6
Note
In the first example, one of possible optimal solutions is to insert value
In the second example, there is only one optimal solution: to insert
In the third example, optimal answer is to leave program untouched, so answer will be
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int a[100005],f[100005],g1[100005],g2[100005];int main(void){ int i,n,m,ans=0; scanf("%d%d",&n,&m); for(i=1;i<=n;++i)scanf("%d",&a[i]); a[n+1]=m; for(i=1;i<=n+2;i+=2)f[i]=f[i-2]+a[i]-a[i-1]; for(i=n;i>=1;i-=2)g1[i]=g1[i+2]+a[i+1]-a[i]; for(i=n-1;i>=1;i-=2)g2[i]=g2[i+2]+a[i+1]-a[i]; ans=max(f[n+1],f[n]); if(n%2==0) { for(i=1;i<=n+1;i+=2) { if(a[i]-a[i-1]<=1)continue; ans=max(ans,f[i]-1+g2[i]); } for(i=1;i<=n;i+=2) { if(a[i+1]-a[i]<=1)continue; ans=max(ans,f[i]+a[i+1]-a[i]-1+g2[i+2]); } } else { for(i=1;i<=n+1;i+=2) { if(a[i]-a[i-1]<=1)continue; ans=max(ans,f[i]-1+g1[i]); } for(i=1;i<=n;i+=2) { if(a[i+1]-a[i]<=1)continue; ans=max(ans,f[i]+a[i+1]-a[i]-1+g1[i+2]); } } printf("%d\n",ans); return 0;}