Link:

传送门

A:

由于每个颜色只染色一次就确定了所有要染色的区间

要求染色的次数其实就是求区间最多嵌套多少层,如果有区间相交则无解

以上操作明显可以将左端点排序后用栈来维护

#include <bits/stdc++.h>

using namespace std;
#define X first
#define Y second
#define pb push_back
typedef double db;
typedef long long ll;
typedef pair<int,int> P;
const int MAXN=2e5+10;
struct node{int x,d,col;};
node dat[MAXN];int st[MAXN],top;
int n,x,l[MAXN],r[MAXN],cur,res,tot;
bool cmp(node a,node b){return a.x==b.x?a.d<b.d:a.x<b.x;}

int main()
{
    scanf("%d",&n);
    memset(l,0x3f,sizeof(l));
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        l[x]=min(l[x],i),r[x]=max(r[x],i);
        if(!x) dat[++tot]=node{i,0,0};
    }
    for(int i=1;i<=n;i++)
        if(r[i]) dat[++tot]=node{l[i],0,i},dat[++tot]=node{r[i],1,i};
    sort(dat+1,dat+tot+1,cmp);
    
    for(int i=1;i<=tot;i++)
    {//注意0代表没有颜色要特殊处理 
        if(!dat[i].col)
        {
            if(top) return puts("-1"),0;
            else continue;
        }
        if(!dat[i].d)
            st[++top]=dat[i].col,cur++;
        else
        {
            if(dat[i].col!=st[top])
                return puts("-1"),0;
            top--;cur--;
        }
        res=max(res,cur);
    }
    printf("%d",res);
    return 0;
}
Problem A

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2022-01-16
  • 2021-07-13
  • 2021-11-27
猜你喜欢
  • 2021-09-26
  • 2021-10-06
  • 2021-08-09
  • 2021-09-25
  • 2021-10-18
  • 2021-12-01
  • 2021-06-24
相关资源
相似解决方案