cf Educational Codeforces Round 46 B. Light It Up

原题:
B. Light It Up
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are “lights on” and “lights off”). Unfortunately, some program is already installed into the lamp.
The lamp allows only good programs. Good program can be represented as a non-empty array a, where
0

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

const int maxn=100001;

int a[maxn];
ll sum1[maxn],sum2[maxn];
unordered_set<int> us;
int n,m;


int main()
{

    ios::sync_with_stdio(false);
    while(cin>>n>>m)
    {
        us.clear();
        memset(sum1,0,sizeof(sum1));
        memset(sum2,0,sizeof(sum2));
        us.insert(0);
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            us.insert(a[i]);
        }
        a[n+1]=m;


        int flag=1;
        ll pre=0;
        for(int i=1;i<=n+1;i++)
        {
            if(flag)
            {
                sum1[i]=sum1[i-1]+(ll)a[i]-pre;
                sum2[i]=sum2[i-1];
            }
            else
            {
                sum1[i]=sum1[i-1];
                sum2[i]=sum2[i-1]+(ll)a[i]-pre;
            }
            pre=a[i];

            if(flag)
                flag=0;
            else
                flag=1;
        }
        ll ans=sum1[n+1];
        ll tmp=-1;
        for(int i=1;i<=n;i++)
        {
            tmp=-1;
            if(us.find(a[i]-1)==us.end())
            {

                tmp=sum1[i]-1+sum2[n+1]-sum2[i];
            }
            ans=max(ans,tmp);

            if(us.find(a[i]+1)==us.end())
            {
                tmp=sum1[i]+a[i+1]-a[i]-1+sum2[n+1]-sum2[i+1];
            }
            ans=max(ans,tmp);
        }

        cout<<ans<<endl;
    }
    return 0;
}

思路:

要想使得灯亮的时间最长,插入的状态一定在ai的左侧或者在ai的右侧,那么枚举ai-1和ai+1,依次判断并更新最大值即可。

另外,可以用两个数组sum1记录灯点亮的累加时间,sum2记录灯熄灭的累加时间,这样在插入ai-1一个状态ai-1后面的灯点亮的时间变成了熄灭的时间,熄灭的时间变成点亮的时间,结果为sum1[i]-1+sum2[n+1]-sum2[i],同理在ai+1插入状态。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值