Paint the Digits

时间:2019-09-15
本文章向大家介绍Paint the Digits,主要包括Paint the Digits使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

C - Paint the Digits

思路:这道题就只需要利用单调栈,将整个数组扫一遍,求得的最后的栈内元素(要求全部小于非栈内元素)的颜色为1,其余为2

那么怎么实现呢?求最后的栈内元素(要求全部小于非栈内元素)的方法:用一个变量记录下最小的被交换的栈元素(这里需要将由于元素相等而交换的情况派除在外)

int first=inf;
for(int i=1;i<=n;++i)
{
    while((!s.empty())&&s.top()>=a[i])
    {
        if(s.top()!=a[i])     //将由于元素相等而交换的情况派除在外
        first=min(fi,s.top());
        s.pop();
    }
    s.push(a[i]);
}
while(s.top()>fi&&fi&&(!s.empty())) //最后的栈内元素要求全部小于非栈内元素
    s.pop();  

然后就是考虑不存在的情况,将栈内元素全部标记成1之后,在标记栈外元素的时候,分别比较前后两个数的大小,若后面的比前面的小,则不存在

代码:

// Created by CAD on 2019/9/15.
#include <bits/stdc++.h>

#define fi first
#define inf 0x3f3f3f3f
#define mst(name, value) memset(name,value,sizeof(name))
using namespace std;

stack<int>s;
const int maxn=2e5+5;
int a[maxn];
int t[maxn];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T;  cin>>T;
    while(T--)
    {
        mst(t,0);
        while(!s.empty()) s.pop();
        int n;cin>>n;
        string str;
        cin>>str;
        for(int i=1;i<=n;++i)
            a[i]=str[i-1]-'0';
        int first=inf;
        for(int i=1;i<=n;++i)
        {
            while((!s.empty())&&s.top()>=a[i])
            {
                if(s.top()!=a[i])
                first=min(fi,s.top());
                s.pop();
            }
            s.push(a[i]);
        }
        while(s.top()>fi&&fi&&(!s.empty())) s.pop();
        for(int i=n;i>=1;--i)
            if(a[i]<s.top()) s.pop(),t[i]=1;
            else if(a[i]==s.top()) t[i]=1;
        bool flag=true;
        int temp=0;
        for(int i=1;i<=n;++i)
            if(!t[i])
            {
                if (a[i]<temp)
                {
                    flag=false;
                    break;
                } else t[i]=2,temp=a[i];
            }
        if(flag)
        {
            for(int i=1;i<=n;++i) cout<<t[i];
            cout<<endl;
        }
        else cout<<'-'<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/CADCADCAD/p/11522527.html