题解:CF1849D Array Painting

· · 题解

分析

我们发现,一段连续的非 0 数可以花费一个金币把它们全染成红色,如果这段数里有 2 就可以把两端的 0 也染红,否则只能把一端的 0 染红。

考虑开一个数组存砖块颜色,先染存在 2 的非 0 串 ,再染不存在 2 的非 0 串,最后染 0。

坑点: 在染不存在 2 的非 0 串时,若其两边的 0 都未被染过色,优先染与循环方向相反的。

代码

#include<bits/stdc++.h>
using namespace std;
int n,a[200002],t[200002],ans;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++)   scanf("%d",&a[i]);
    for(int i=1;i<=n;i++){
        if(a[i]==2&&!t[i]){
            ans++;
            t[i]=1;
            int j=i,d=i;
            while(a[(++j)]) t[j]=1;
            while(a[(--d)]) t[d]=1;
            t[d]=1;
            t[j]=1;
        }
    }
    for(int i=1;i<=n;i++){
        if(a[i]==1&&!t[i]){
            ans++;
            int cun=i-1;
            t[i]=1;
            while(a[(++i)]){
                t[i]=1;
            }
            if(cun<1||t[cun])   t[i]=1;
            else    t[cun]=1; 
        }
    }
    for(int i=1;i<=n;i++) if(!t[i]) ans++;
    cout<<ans;
    return 0;
}