[CF1479B1/CF1480D1] Painting the Array I


[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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM