Los sort Valley P1155 dual-stack

Los sort Valley P1155 dual-stack

Topic links: https://www.luogu.com.cn/problem/P1155

The ascending order of the stack can be known, should be maintained monotonous stack, such that the top element is smaller than the bottom of the stack element, which is a reprint from the stack to the stack by stack

Now consider a [i] can not enter the stack 1:

Just such a problem, if present in the sequence A [I] <A J , if the order of the sequence of the a [i], a [j ] stack, it is not certain, since the stack order of a [j ], a [i], a non-ascending

But i, j does not necessarily adjacent, we may be in a position k: i <k <j time, so that a [i] can pop up, this time a [i], a [j] you can enter the same a stack of

When a [i] can push a first requires a [i] <s1.top ():

(1) The stack 2 is empty.

Because the present time even if i <j <k, a [k] <a [i] <a [j], may allow a [j] into the stack 2, with a solution

(2) two non-empty stack, and the sequence does not exist i <j <k, a [k] <a [i] <a [j], a [j]> s2.top ()

if a[i]->s1
    if a[j]->s1
        because a[k]<a[i], so s1中有a[i]<a[j],且a[i]出栈晚于a[j],排除
    if a[j]->s2
        s2非空,分析一下什么元素会进s2.
        假设s1和s2栈顶元素相等(当然题中不可能发生)那应该是弹s1较优,因为字典序更小。
        假设s1栈顶元素>s2栈顶元素,不可能,因为字典序也不是最优
        所以s2.top()>s1.top(),又因为a[j]>s2.top(),
        所以a[j]>s2.top()>s1.top()>a[i]>a[k]
        翻译一下这是啥意思呢,就是在a[k]未弹出时,a[j]没有地方可去,这是不行的
        

So write a judgment function, greedy resolved on the line.

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

const int N=1e3+10;
int n,a[N],now=1;
vector<char> ans;
stack<int> s,t;
void push1(int u){s.push(u);ans.push_back('a');}
void push2(int u){t.push(u);ans.push_back('c');}
void pop1(){s.pop();ans.push_back('b');}
void pop2(){t.pop();ans.push_back('d');}
bool check(int k)//a[k]<s.top()
{
    if(t.empty()) return 1;
    int i,j;//k<i<j
    for(i=k+1;i<=n;i++) if(a[i]>a[k]&&a[i]>t.top()) break;
    for(j=i+1;j<=n;j++) if(a[j]<a[k]) return 0;
    return 1;   
}
int main()
{
    scanf("%d",&n);
    int cnt=1;
    s.push(1e4),t.push(1e4);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    bool ok=true;
    for(int i=1;i<=(n<<1);i++)
    {
        if(s.top()==now) {pop1();now++;continue;}
        if(t.top()==now) {pop2();now++;continue;}
        if(cnt<=n&&a[cnt]<s.top()&&check(cnt)) {push1(a[cnt++]);continue;}
        if(cnt<=n&&a[cnt]<t.top()) {push2(a[cnt++]);continue;}
        ok=false;break;
    }
    if(ok)
    {
        for(int i=0;i<ans.size();i++) 
            if(i==0) putchar(ans[i]);
            else printf(" %c",ans[i]);;
    }
    else puts("0");
    return 0;
}

Guess you like

Origin www.cnblogs.com/JWizard/p/12323182.html