cf Educational Codeforces Round 46 B. Light It Up

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tengfei461807914/article/details/82010724

原题:
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插入状态。

猜你喜欢

转载自blog.csdn.net/tengfei461807914/article/details/82010724