[CF1479B1/CF1480D1] Painting the Array I

Description

将一个序列拆成两个子序列,然后每个子序列中相邻相同的元素只保留一个,最大化剩下元素的个数。

Solution

贪心,决定每个元素 \(a[i]\) 放在哪里,取决于 \(a[i],a[i+1]\) 和当前两个已有子序列的末尾

#include <bits/stdc++.h>
using namespace std;

int n;
int a[100005];

signed main()
{
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    a[n+1]=-1;
    int top1=-1,top2=-1,ans=0;
    for(int i=1;i<=n;i++)
    {
        if(a[i]==top1 && a[i]==top2) continue;
        else if(a[i]==top1) 
        {
            top2=a[i];
            ans++;
        }
        else if(a[i]==top2)
        {
            top1=a[i];
            ans++;
        }
        else 
        {
            ans++;
            if(a[i+1]==top1 && a[i+1]!=top2) 
            {
                top1=a[i];
            }
            else if(a[i+1]!=top1 && a[i+1]==top2)
            {
                top2=a[i];
            }
            else 
            {
                top1=a[i];
            }
        }
    }
    cout<<ans<<endl;
}

相关文章:

  • 2021-07-14
  • 2022-12-23
  • 2021-07-23
  • 2022-12-23
  • 2021-05-15
猜你喜欢
  • 2022-12-23
  • 2021-08-29
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
相关资源
相似解决方案