Problem:


Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1



Sample input:
3
1 2 1


Sample output:
1
1
2

Submission status: Accepted

Solution code:
N = int(input())
prob = list(map(int, input().split()))
ans = []
for i in reversed(range(N)):
  boo = False
  for j in reversed(range(i + 1)):
    if prob[j] == j + 1:
      boo = True
      ans.append(j + 1)
      del prob[j]
      break
  if not boo:
    break
if len(ans) == N:
  for x in reversed(ans):
    print(x)
else:
  print(-1)

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int,input().split(" ")))
used = [0] * N
n = N
ans = []
for i in range(N):
    index = n
    flg = True
    for j in range(N-1,-1,-1):
        if used[j] == 0:
            if b[j] == index:
                used[j] = 1
                ans.append(b[j])
                flg = False
                break
            else:
                index -= 1
    if flg:
        print("-1")
        exit(0)
    n -= 1


print(*ans[::-1])

Submission status: Accepted

Solution code:
import sys
N=int(input())
L=[int(i)-1 for i in input().split()]
M=[]
while True:
    flag=0
    if len(L)==0:
        for m in M[::-1]:
            print(m+1)
        sys.exit()
    for i in range(len(L)-1,-1,-1):
        if L[i]==i:
            s = L.pop(i)
            M.append(s)
            flag=1
            break
    if flag==0 and len(L)!=0:
        print(-1)
        sys.exit()

Submission status: Accepted

Solution code:
input()
nums  = list(map(int, input().split()))

def low(lis, n):
    return [
        l for l in lis if l <= n
    ]

def rev_idx(lis, n):
    return [
        i for i, e in enumerate(lis[::-1]) if e == n
    ]


try:
    sort = sorted(list(set(nums)))[1:]
    order = low(nums, 1)
    order[0]
    for i, n in enumerate(sort):
        lows = low(nums, n)
        for index in rev_idx(lows, n):
            if (n + index - 1) > len(order):
                raise Exception
            order.insert(n + index - 1, n)
    for o in order:
        print(o)
except:
    print(-1)

Submission status: Accepted

Solution code:
import numpy as np

def main():
    n = int(input())
    a = []
    b = list(map(int, input().rstrip().split(" ")))

    for i in range(n):
        ind = -1
        for j in range(len(b)):
            if b[j] == j + 1:
                if j + 1 == len(b):
                    ind = j
                elif b[j+1] != j + 2:
                    ind = j
        if ind >= 0:
            a.append(b.pop(ind))

    a.reverse()
    if len(a) == n:
        for v in a:
            print(v)
    else:
        print(-1)



if __name__ == '__main__':
   main()

Submission status: Accepted

Solution code:
from sys import stdin, stdout
from decimal import Decimal
from random import randint
PEPS = 1e-10
INF = float('inf')


def sqr(a):
    return a * a


def dist(a, b = (0, 0)):
    return sqrt(sqr(a[0] - b[0]) + sqr(a[1] - b[1]))


def s_dist(a, b = (0, 0)):
    return (sqr(a[0] - b[0]) + sqr(a[1] - b[1]))


def dist3(a, b = (0, 0, 0)):
    return sqrt(sqr(a[0] - b[0]) + sqr(a[1] - b[1]) + sqr(a[2] - b[2]))


def s_dist3(a, b = (0, 0, 0)):
    return (sqr(a[0] - b[0]) + sqr(a[1] - b[1]) + sqr(a[2] - b[2]))


def trans(p, al):
    return (p[0] * cos(al) + p[1] * sin(al), - p[0] * sin(al) + p[1] * cos(al))


def get_angle(a, b, c):
    cos_al = (sqr(a) + sqr(b) - sqr(c)) / (2 * a * b)
    return acos(cos_al)


def write_float(ans):
    stdout.write(str('%.13f' % ans) + '\n')


def get_hight(pt1, pt2, pt3):
    a = (pt2[0] - pt1[0], pt2[1] - pt1[1])
    b = (pt3[0] - pt1[0], pt3[1] - pt1[1])
    return abs(a[0] * b[1] - a[1] * b[0]) / dist(pt1, pt2)


def get_square(pt1, pt2, pt3):
    a = (pt2[0] - pt1[0], pt2[1] - pt1[1])
    b = (pt3[0] - pt2[0], pt3[1] - pt2[1])
    return (a[0] * b[-1] - a[1] * b[0]) / 2


def sign(v):
    if v > 0:
        return 1
    elif v < 0:
        return -1
    else:
        return 0


def inn(pt, triangle):
    signs = set()
    signs.add(sign(get_square(triangle[0], triangle[1], pt)))
    signs.add(sign(get_square(triangle[1], triangle[2], pt)))
    signs.add(sign(get_square(triangle[2], triangle[0], pt)))
    return len(signs) == 1


def inter_in(a, b):
    return dist((a[0], a[1]), (b[0], b[1])) < a[-1] + b[-1]


def inter_in3(a, b):
    return dist3(a[:-1], b[:-1]) < a[-1] + b[-1]


def shift(what, wth):
    return (what[0] - wth[0], what[1] - wth[1])


n = int(stdin.readline())
vl = list(map(int, stdin.readline().split()))
ans = []

while len(vl):
    for i in range(len(vl) - 1, -1, -1):
        if vl[i] == i + 1:
            ans.append(i + 1)
            vl = vl[:i] + vl[i + 1:]
            break
    else:
        stdout.write('-1\n')
        break


if len(ans) == n:
    ans = ans[::-1]
    stdout.write('\n'.join(list(map(str, ans))))

Submission status: Accepted

Solution code:
N = int(input())
b = [int(num) for num in input().split()]
queue = [[b,[]]]

def bfs(queue):
    c,prev = queue.pop(0)
    cnt = len(c)-1
    while cnt >= 0:
        if c[cnt] == cnt+1:
            del c[cnt]
            prev = [cnt+1] + prev
            queue.append([c,prev])
            break
        cnt -= 1
    return queue

ans = -1
while queue != []:
    if queue[-1][0] == []:
        ans = queue[-1]
        break
    queue = bfs(queue)
        
if ans == -1:
    print(ans)
else:
    for num in ans[1]:
        print(num)

Submission status: Accepted

Solution code:
N=int(input())
b=[int(i) for i in input().split()]
a=[]
try:
    while len(b)>0:
        a2=max([j for i,j in enumerate(b) if b[i]==i+1])
        a.insert(0,a2)
        x=b.pop(a2-1)
    for n in a:
        print(n)
except:
    print(-1)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    a = LI()

    r = []
    while a:
        l = len(a)
        nf = False
        for i in range(l-1,-1,-1):
            if a[i] == i+1:
                r.append(i+1)
                a = a[:i] + a[i+1:]
                nf = True
                break
        if not nf:
            return -1

    return '\n'.join(map(str, r[::-1]))


print(main())

Submission status: Accepted

Solution code:
N=int(input())
b=[int(i) for i in input().split()]
ans=[]
M=N
while(M>0):
    j=-1
    for i in range(M)[::-1]:
        if b[i]==i+1:
            j=i
            break
    if j==-1:
        print(-1)
        exit()
    a=[]
    for i in range(M):
        if j!=i:
            a.append(b[i])
    ans.append(b[j])
    b=[i for i in a]
    M=len(b)
for line in ans[::-1]:
    print(line)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(20000000)
input = sys.stdin.readline
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
    if i+1 < a[i]:
        print(-1)
        exit()
 
def dfs(x,ans,so):
        if x == n:
                if ans == a:
                        so = so[::-1]
                        for i in so:
                                print(i)
                        exit()
                return 0
        for i in range(len(ans)-1,-1,-1):
            if ans[i] == i+1:
                ans.pop(i)
                so.append(i+1)
                dfs(x+1,ans,so)
                ans.insert(i,i+1)
                so.pop()
        return -1
print(dfs(0,a,[]))

Submission status: Accepted

Solution code:
n=int(input())
m=list(map(int,input().split()))
ans=[]
for i in range(n):
  for j in range(n-1-i,-1,-1):
    if not m[j]==j+1:
      continue
    #m[j]==j
    ans.append(j+1)
    m=m[:j]+m[j+1:]
    break
if not len(m)==0:
  print(-1)
else:
  for i in range(n):
    print(ans[n-1-i])

Submission status: Accepted

Solution code:
n=int(input())
B=list(map(int,input().split()))
A=[]
while B:
    for i,b in enumerate(B[::-1]):
        idx=len(B)-i
        if b==idx:
            A.append(b)
            B.pop(idx-1)
            break
    else:
        break
if B:
    print(-1)
else:
    for a in A[::-1]:
        print(a)

Submission status: Accepted

Solution code:
import sys

N=int(input())
s=list(map(int,input().split()))

s=s+[10**6]
ans=[0]*N


for i in range (N):
    m=-1
    for j in range (N-i):
        if s[j]==j+1:
            m=j
    if m<0:
        print(m)
        sys.exit()
    
    ans[N-i-1]=m+1
    
    for j in range (m,N):
        s[j]=s[j+1]
        
    
for i in range(N): print(ans[i])

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    B = list(map(int, input().split()))
    ans = [0] * N
    for i in range(N):
        idx = 0
        for j in range(N-i):
            if B[j] == j+1:
                idx = j+1
        if idx == 0:
            print(-1)
            return
        ans[i] = idx
        B = B[:idx-1] + B[idx:]
    for a in ans[::-1]:
        print(a)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int, input().split()))

ans=[]
while b:
    for i in reversed(range(len(b))):
        if i==b[i]-1:
            b.remove(b[i])
            ans.append(i)
            break
        if i==0:
            print(-1)
            exit()
ans.reverse()
for i in ans:
    print(i+1)

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int,input().split()))
answer = []

def check(series):
    L = len(series)
    if L == 0:
        return(True)
    matching = [False for _ in range(L)]
    maxMatchIndex = -1
    for i in range(L):
        num = series[i]
        match = num == i+1
        if match:
            matching[i] = True
            maxMatchIndex = i
    if maxMatchIndex == -1:
        return(False)
    answer.append(maxMatchIndex + 1)
    del series[maxMatchIndex]
    return(check(series))

res = check(b)
if res:
    answer.reverse()
    for ans in answer:
        print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]

n = int(input())
a = list(map(int, input().split()))
ans = []
for i in range(n):
	for j in range(n-i-1, -1, -1):
		if a[j] == j+1:
			ans.append(j+1)
			a.pop(j)
			break
	else:
		print(-1)
		sys.exit()
print(*ans[::-1], sep="\n")

Submission status: Accepted

Solution code:
n = int(input())
b = [int(i) for i in input().split()]
a = []
while b:
    p = 0
    for i in range(len(b)-1,-1,-1):
        if b[i]==i+1:
            p = b.pop(i)
            break
    if p: a.append(p)
    else: break
if p:
    for i in a[::-1]: print(i)
else: print(-1)

Submission status: Accepted

Solution code:
import sys

N = input()
b = list(map(int,input().split()))

max_b = max(b)
ans = []
flag = 0

while len(b) != 0:
    for i in range(min(max_b-1,len(b)-1),-1,-1):
        if b[i] == i+1:
            flag = 1
            b.pop(i)
            ans.append(i+1)
            break
    if flag == 0:
        print(-1)
        sys.exit()
    flag = 0

for i in reversed(ans):
    print(i)

Submission status: Accepted

Solution code:
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys
import math

sys.setrecursionlimit(1000000)

INF = 10 ** 18
MOD = 10 ** 9 + 7

N = input()
b = map(int, raw_input().split())
ans = []
for _ in range(N):
    pos = -1
    for i in range(len(b)):
        if b[i] == i + 1:
            pos = i
    if pos < 0:
        print -1
        exit()
    ans += [b[pos]]
    b = b[:pos] + b[pos + 1:]
for p in ans[::-1]:
    print p

Submission status: Accepted

Solution code:
N = int(input())

B = list(map(int,input().split()))

ans = []
for k in range(N):
    flag = 1
    for i in range(len(B)):
        j = len(B)-i-1
        if j+1 == B[j]:
            ans.insert(0,B[j])
            B.pop(j)
            flag = 0
            break
    if flag == 1:
        ans = -1
        break

if ans == -1:
    print(ans)
else:
    for a in ans:
        print(a)

Submission status: Accepted

Solution code:
n=int(input())
b=[int(i) for i in input().split()]
ans=[]
result=True
while len(b):
    for i,j in enumerate(b[::-1]):
        if len(b)-i==j:
            ans.append(j)
            b.pop(len(b)-(i+1))
            break
    else:
        result=False
        break
if result:
    for i in ans[::-1]:
        print(i)
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(int, input().split()))

ans = [0]

for b in B:
    ans.insert(b-1, b)

if sum(ans[:N]) == sum(B):
    for i in range(N):
        print(ans[i])
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(int,input().split()))

L = []
flag = 1
while len(B):
    for i,b in enumerate(B[::-1]):
        if len(B)-i == b:
            L.append(b)
            B.pop(len(B)-i-1)
            break
    else:
        flag = 0
        break

if flag:
    for s in L[::-1]:
        print(s)
else:
    print(-1)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N = int(input())
    B = list(map(int, input().split()))

    ans = []
    for n in range(N, 0, -1):
        for i in range(N-1, -1, -1):
            if not B[i]:
                continue
            if B[i] == n:
                ans.append(n)
                B[i] = 0
                break
            n -= 1
        else:
            print(-1)
            return
    print(*ans[::-1], sep='\n')

input = lambda: stdin.readline()
main()

Submission status: Accepted

Solution code:
# /usr/bin/python
# -*- coding: utf-8 -*-
#
import sys
import math



def solve(b):
  ret = []
  while len(b) > 0:
    dct = [] # list of index
    for i in range(len(b)):
      if b[i] == i+1:
        dct.append(i)
    if len(dct) == 0:
      return [-1]
    else:
      ret.append(dct[-1]+1)
      b.pop(dct[-1])
  return ret[::-1]


N = int(input())
B = list(map(int, input().split()))

for i in solve(B):
  print(i)

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(int, input().split()))


ans = []
while B:
    itr = list(enumerate(B, start=1))[::-1]
    for i, b in itr:
        if i == b:
            del B[i - 1]
            ans.append(b)
            break
    else:
        print(-1)
        exit()

print(*ans[::-1], sep='\n')

Submission status: Accepted

Solution code:
n = int(input())
b = list(map(int,input().split()))[::-1]
a = []
while b:
    for i,v in enumerate(b):
        if v == len(b)-i:
            a.append(v)
            b.pop(i)
            break
    else:
        print(-1)
        exit()

for ans in a[::-1]:
    print(ans)

Submission status: Accepted

Solution code:
N = int(input())
b = map(int,input().split())
b_ = [int(s) for s in b]
ans = []
for i in range(N):
    for j in range(len(b_),0,-1):
        if j == b_[j-1]:
            del b_[j-1]
            ans.append(j)
            break
if len(ans) == N:
    for i in reversed(ans):
        print(i)
else:
    print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
acts = []
while True:
    for i in range(len(a)):
        idx = len(a)-i-1
        if a[idx] == idx+1:
            a.pop(idx)
            acts.append(idx+1)
            break
    else:
        print('-1')
        break
    if len(a) == 0:
        acts.reverse()
        print('\n'.join(map(str,acts)))
        break

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int, input().split()))

for i in range(N):
	if b[i] > i+1:
		print(-1)
		exit()

a = []
for i in range(N):
	for j in range(len(b)-1, -1, -1):
		if b[j] == j+1:
			a += [b.pop(j)]
			break
a.reverse()
			
if len(b) != 0:
	print(-1)
else:
	for ai in a:
		print(ai)

Submission status: Accepted

Solution code:
n = int(input())
bb = list(map(int, input().split()))
ans = [0]*n
for k in range(n,0,-1):
  for i,num in enumerate(bb[::-1]):
    if num+i == k:
      ans[k-1] = bb.pop(-i-1)
      break
  else:
    print(-1)
    exit()
for i in ans:
  print(i)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    B = [int(_) for _ in input().split()]

    #出力用
    outs = []

    for i in range(N):
        for k in range(N-1-i,-1,-1):
            if B[k] == k+1:
                del B[k]
                outs.insert(0,k+1)
                break
        else:
            print(-1)
            return

    for out in outs:
        print(out)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def a_limited_insertion(N, B):
    """
    空の数列Aに対し、
    ・i回目の操作では i<=j<=iを満たす整数jを選び、Aの先頭からj番目にjを挿入する
    という操作をN回行う。その後A, Bが一致することがあるか判定し、あるなら
    それを達成する操作手順を1つ示せ。
    """

    # この問題を言い換える。
    # 「数列Bに対し、左からk番目(1-based)の要素がkであるならば、
    # それを取り除くことができる。数列Bを空にできるか？」
    # このとき、取り除ける要素のうち、最も右側にあるものを選ぶほかない。
    # なぜなら、そうでないものを取り除くと、二度と取り除くことができない要素が
    # 生じるからである。
    # e.g. B: * * 3 * * 6 に対して3を取り除くと、6が取り除けなくなる
    # これをシミュレートすれば、O(N**2)時間で判定できる。
    ans = []
    while B:
        for k in range(len(B) - 1, -1, -1):
            if B[k] == k + 1:
                ans.append(k + 1)
                B.pop(k)
                break
        else:
            return -1
    # 逆操作での解を得たので、それを反転させると元の操作での解になる
    return ' '.join(map(str, reversed(ans)))

N = int(input())
B = [int(i) for i in input().split()]
print(a_limited_insertion(N, B))

Submission status: Accepted

Solution code:
N=int(input())
b=list(map(int,input().split()))

#print(b)
ans=[]
for i in range(N):
    for j in range(len(b)):
        if b[len(b)-1-j]==len(b)-j:
            ans.append(len(b)-j)
            del b[len(b)-1-j]
            #print(b)
            break
if b!=[]:
    print(-1)
else:
    ans=ans[::-1]
    for i in range(N):
        print(ans[i])

Submission status: Accepted

Solution code:
N = int(input())
b_list = list(map(int, input().split()))

ans = []
while len(b_list) > 0:
    f = -1
    for i in range(len(b_list)):
        if b_list[i] == i + 1:
            f = i
    if f == -1:
        print(-1)
        exit()
    ans.append(b_list[f])
    b_list.pop(f)

ans = reversed(ans)
for a in ans:
    print(a)

Submission status: Accepted

Solution code:
N = int(input())
b_list = list(map(int, input().split()))
rev_b = reversed(b_list)

ans = []

while len(b_list) > 0:
    f = -1
    for i in range(len(b_list)):
        if b_list[i] == i + 1:
            f = i
    if f == -1:
        print(-1)
        exit()
    ans.append(b_list[f])
    b_list.pop(f)
ans = reversed(ans)
for a in ans:
    print(a)

Submission status: Accepted

Solution code:
N=int(input())
b=list(map(int,input().split()))

b.reverse()
ans=[]
disable=False

for i in range(N):
    for j in range(len(b)):
        if b[j]==len(b)-j:
            ans.append(b.pop(j))
            break
        if j==len(b)-1:
            disable=True
            ans=[-1]
            break
    if disable:
        break

ans.reverse()
for a in ans:
    print(a)

Submission status: Accepted

Solution code:
n = int(input())

b = list(map(int,input().split()))

ans = []

for i in list(reversed(range(n))):
    for j in list(reversed(range(i+1))):
        if (b[j] == j+1):
            ans.append(j+1)
            del b[j]
            break
        if j == 0:
            print("-1")
            exit()

ans = list(reversed(ans))

for i in range(n):print(ans[i])

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(int, input().split()))
A_rev = []
import sys
while(len(B)):
    max = -1
    for i in range(len(B)):
        if B[i] == i+1:
            max = i
    if max == -1:
        print(-1)
        sys.exit()
    A_rev.append(B[max])
    B.pop(max)
for a in A_rev[::-1]:
    print(a)

Submission status: Accepted

Solution code:
import sys
import re

N = input()
b = [int(item) for item in re.split(r"\s", input())]

out_list = []

while len(b) > 0:
    for i in range(len(b)):
        index = len(b) - 1 - i
        if b[index] == index + 1:
            out_list.append(b.pop(index))
            break
    else:
        # 最後まで探索が終ってしまう->-1
        print(-1)
        sys.exit()

else:
    for item in out_list[::-1]:
        print(item)

Submission status: Accepted

Solution code:
# coding:utf-8

import sys

INF = float('inf')
MOD = 10 ** 9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


def main():
    n = II()
    B = LI()

    res = []
    T = B[:]
    for _ in range(n):
        for i in range(len(T))[::-1]:
            if i + 1 == T[i]:
                res.append(T[i])
                T = T[:i] + T[i+1:]
                break
        else:
            print(-1)
            return 0

    print(*[i for i in reversed(res)], sep='\n')
    return 1


main()

Submission status: Accepted

Solution code:
n = int(input())
b = [int(_) for _ in input().split(' ')]

answer = []
p = True
for i in range(n, 0, -1):
    for j in range(i, 0, -1):
        if b[j - 1] == j:
            answer.append(j)
            b.pop(j - 1)
            break
        elif b[j - 1] > j:
            p = False

if p:
    answer.reverse()
    for i in answer:
        print(i)
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
b = list(map(int, input().split()))

from queue import Queue
q = Queue()
ans = Queue()

import numpy as np
n = np.array(n)


def bfs(b):
    q.put(b)
    ans.put([])

    while q.empty() == False:
        p = q.get()
        a = ans.get()

        if p == []:
            break

        if p[0] != 1:
            continue

        m = len(p)

        for i in range(m-1, -1, -1):
            if p[i] == i+1:
                q.put(p[:i]+p[i+1:])
                ans.put(a+[i+1])
                break


    if p == []:
        a = a[::-1]
        for aa in a:
            print(aa)
    else:
        print(-1)


bfs(b)

Submission status: Accepted

Solution code:
# 入力
N = int(input())
b = list(map(int, input().split()))


# 逆順から操作手順を求める
def f(c):
    j = max([j for j, x in enumerate(c, 1) if j == x], default=0)
    return (
        f(c[:(j-1)] + c[j:]) + [j] if j and len(c) >= 2 else
        [j] if j and len(c) == 1 else
        []
    )


res = f(b)

# 出力
ans = '\n'.join(map(str, res)) if len(res) == N else -1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
b = list(map(int,input().split()))
l = []
while not b==[]:
    k=0
    for i in range(len(b)-1,-1,-1):
        if i+1==b[i]:
            l.append(b[i])
            del b[i]
            k=1
            break
    if not k:
        print(-1)
        exit()
l.reverse()
for l_ in l:
    print(l_)

Submission status: Accepted

Solution code:
n = int(input())

l = input().split()

res = []

for i in range(n):
    
    
    for j in range(len(l)-1,-1,-1):
        if(l[j] == str(j+1)):
            res.append(l[j])
            del(l[j])
            break
    


            

if(l != []):
    print(-1)
else:
    print("\n".join(res[::-1]))

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(input())
def pf(s): return print(s, flush=True)


N = I()
b = LI()

result = []
while True:
    #  print(b)
    for i in range(1, len(b)+1):
        #  print(i)
        if b[-i] == len(b)-i+1:
            #  print('break')
            result.append(b[-i])
            b.pop(-i)
            break
    else:
        if not b:
            break
        print(-1)
        exit()
for i in result[::-1]:
    print(i)

Submission status: Accepted

Solution code:
N = int(input())
B = [int(x) - 1 for x in input().split()]
#  print('b', B)
ans = []
while B:
    popped = -1
    for i in reversed(range(len(B))):
        if B[i] == i:
            ans.append(i + 1)
            popped = B.pop(i)
            break
    if popped == -1:
        print(-1)
        quit()
print(*ans[::-1], sep="\n")

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def pf(s): return print(s, flush=True)


N = I()
b = LI()

result = []
while True:
    #  print(b)
    for i in range(1, len(b)+1):
        #  print(i)
        if b[-i] == len(b)-i+1:
            #  print('break')
            result.append(b[-i])
            b.pop(-i)
            break
    else:
        if not b:
            break
        print(-1)
        exit()
for i in result[::-1]:
    print(i)

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def pf(s): return print(s, flush=True)


N = I()
b = LI()

result = []
while True:
    #  print(b)
    for i in range(1, len(b)+1):
        #  print(i)
        if b[-i] == len(b)-i+1:
            #  print('break')
            result.append(b[-i])
            b.pop(-i)
            break
    else:
        if not b:
            break
        print(-1)
        exit()
for i in result[::-1]:
    print(i)

Submission status: Accepted

Solution code:
import sys


n = int(input())
b = list(map(int, input().split()))
ope = []
i = n
while i > 0:
    flag = 0
    j = i
    while j > 0:
        if b[j - 1] == j:
            b.pop(j - 1)
            i -= 1
            ope.insert(0, j)
            flag = 1
            break
        j -= 1
    if flag == 0:
        print(-1)
        sys.exit()
for i in ope:
    print(i)

Submission status: Accepted

Solution code:
#! usr/bin/env python
# -*- coding: utf-8 -*-


def main():
    N = int(input())
    B = list(map(int, input().split()))

    ans = [-1] * N
    for i in range(N):
        cur = -1
        for j in range(len(B)):
            if B[j] == j + 1:
                cur = B[j]

        if cur == -1:
            print(-1)
            exit()

        ans[N-i-1] = cur
        B.pop(cur-1)

    for i in ans:
        print(i)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
b = list(map(int, input().split()))

result = []
for i in range(len(b)):
    for j in reversed(list(range(len(b)))):
        if b[j] == j + 1:
            result.append(b.pop(j))
            break
if len(b) != 0:
    print(-1)
    exit(0)

for result_i in reversed(result):
    print(result_i)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)
#def input():
#    return sys.stdin.readline()[:-1]

'''
n=int(input())
for i in range(n):
    a[i]=int(input())
    a[i],b[i]=map(int,input().split())
a=[int(x) for x in input().split()]
n,m=map(int,input.split())
from operator import itemgetter
a = [(1, "c", 1), (1, "b", 3), (2, "a", 0), (1, "a", 2)]
print(sorted(a))  # 0 番目の要素でソート、先頭の要素が同じなら 1 番目以降の要素も見る
print(sorted(a, key=itemgetter(0)))  # 0 番目の要素だけでソート
print(sorted(a, key=itemgetter(0, 2)))  # 0 番目と 2 番目の要素でソート
print(sorted(a, key=lambda x: x[0] * x[2]))  # 0 番目の要素 * 2 番目の要素でソート
print(sorted(a, reverse=True))  # 降順にソート
a.sort()  # 破壊的にソート、sorted() よりも高速
try: # エラーキャッチ list index out of range
    for i in range():
        k=b[i]
except IndexError as e:
    print(i)
'''

test_data1 = '''\
3
1 2 1
'''

test_data2 = '''\
2 3 0
4 5 6
7 8 9
-1 2 -5
'''

test_data3 = '''\
9
1 1 1 2 2 1 2 3 2
'''
td_num=3

def GetTestData(index):
    if index==1:
        return test_data1
    if index==2:
        return test_data2
    if index==3:
        return test_data3

if False:
    with open("../test.txt", mode='w') as f:
        f.write(GetTestData(td_num))
    with open("../test.txt") as f:
        # Start Input code ---------------------------------------
        n=int(f.readline())
        b=list(map(int,f.readline().split()))
        # End Input code ---------------------------------------
else:
    for i in range(1):
        # Start Input code ---------------------------------------
        n=int(input())
        b=list(map(int,input().split()))
        # End Input code ---------------------------------------
#print('n,m,x,y=',n,m,x,y)
ans=[]
#print(b)
cnt=0
while cnt<100 and len(b)>0:
    m=len(b)
    cnt+=1
    flg=False
    for i in range(m):
        #print('i,i+1,m-1-i,b[m-1-i]',i,i+1,m-1-i,b[m-1-i],b)
        if b[m-1-i]==m-i:
            ans.append(b.pop(m-1-i))
            
            flg=True
            break
    if flg==False:
        break
if len(ans)==n:
    for i in range(n):
        print(ans[-i-1])
else:
    print(-1)