码迷,mamicode.com
首页 > 其他好文 > 详细

Codeforces 911E - Stack Sorting

时间:2018-01-25 19:50:28      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:入栈   memset   else   class   turn   com   set   gpo   ace   

911E - Stack Sorting

思路:

用栈来模拟,能pop就pop,记下一个需要pop的数为temp,那么如果栈非空,栈顶肯定大于temp,那么加入栈 栈顶值-1 到 temp 的值,否则加入栈 n 到 1 的值,如果需要加入的数之前已经出现过,答案则不存在。

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define meme(a,b) memset(a,b,sizeof(a))

const int N=2e5+5;
bool vis[N];
int a[N];
stack<int>s;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,k;
    cin>>n>>k;
    int temp=1;
    for(int i=1;i<=k;i++){
        cin>>a[i];
        vis[a[i]]=true;
        s.push(a[i]);
        while(s.size()&&s.top()==temp){
            s.pop();
            temp++;
        }
    }
    while(s.size()&&s.top()>temp||n+1>temp){
        int t;
        if(s.size())t=s.top();
        else t=n+1;
        for(int i=t-1;i>=temp;i--){
            if(vis[i]){
                cout<<-1<<endl;
                return 0;
            }
            else s.push(i),a[++k]=i,vis[i]=true;
        }
        while(s.size()&&s.top()==temp){
            s.pop();
            temp++;
        }
    }
    if(s.size())cout<<-1<<endl;
    else for(int i=1;i<=n;i++)cout<<a[i]<< ;
    cout<<endl;
    return 0;
}

 

Codeforces 911E - Stack Sorting

标签:入栈   memset   else   class   turn   com   set   gpo   ace   

原文地址:https://www.cnblogs.com/widsom/p/8352810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!