Stack

题目描述

ZYT had a magic permutation a1,a2,⋯ ,ana_1,a_2,\cdots, a_na1​,a2​,⋯,an​, and he constructed a sequence b1,b2,⋯bnb_1,b_2,\cdots b_nb1​,b2​,⋯bn​ by the following pseudo code:

Stk is an empty stack
for i = 1 to n :
    while ( Stk is not empty ) and ( Stk's top > a[i] ) : 
        pop Stk
    push a[i]
    b[i]=Stk's size

But he somehow forgot the permutation a{a}a, and only got some k{k}k elements of bib_ibi​.

Construct a permutation a{a}a satisfying these bib_ibi​ , or determine no such permutation exists.

Here a permutation refers to a sequence that contains all integers from 1{1}1 to n{n}n exactly once.

输入描述:

The first line contains two integers n{n}n,k(1≤k≤n){k} (1\leq k\leq n)k(1≤k≤n) — the length of the permutation, the number of  left bib_ibi​.

Then k{k}k lines each contains two integer pi,xip_i,x_ipi​,xi​, denoting that bpi=xib_{p_i}=x_ibpi​​=xi​.

输出描述:

Output one line with n integers a1,a2,⋯ana_1,a_2,\cdots a_na1​,a2​,⋯an​ — a possible permutation.

If no such permutation exists, output one integer -1.

示例1

输入

复制

5 2
2 2
5 4

输出

复制

1 2 5 3 4

示例2

输入

复制

10 1
1 10

输出

复制

-1

备注:

It's guaranteed that n≤106,1≤pi,xi≤nn\leq 10^6,1\leq p_i,x_i\leq nn≤106,1≤pi​,xi​≤n, and ∀i≠j,pi≠pj\forall i\ne j,p_i\ne p_j∀i​=j,pi​​=pj​.

  分析:对于没有给定b的位置,一定往直接单调栈插入元素
         否则根据给定的单调栈大小判断弹掉栈顶的几个元素,如果不够就无解
         每次根据被弹掉的最后一个元素,以及没有弹掉的栈顶元素
         由此,构造出一组拓扑关系
         然后直接做一次拓扑排序即可构造出一组合法解

代码如下:

#include <bits/stdc++.h>
using namespace std;
int n,k,a[1000010];
int main(){
    cin>>n>>k;
    while(k--){
        int x,y;
        cin>>x>>y;
        a[x]=y;//记录数组b的下标和数字
    }
    for(int i=1;i<=n;i++){
        if(!a[i]) a[i]=a[i-1]+1;
        if(a[i]>(a[i-1]+1)){//因为上个数只有出栈和不出两种选择,所以a[i]最多只能比a[i-1]大1,若超过了,说明不可能有这样的序列
            cout<<"-1";
            return 0;
        }
    }
    stack<int> s;//用栈储存所有顶点
    int t=0;

   //拓扑排序
    for(int i=n;i>=1;i--){//从后往前遍历
        while(s.size()<a[i]){//利用这个数前面的那个数一定要比这个数小
            s.push(++t);
        }
        a[i]=s.top();
        s.pop();
    }
    for(int i=1;i<=n;i++){
        cout<<a[i]<<' ';
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值