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:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n = INT()
b = LIST()
ans = deque()

while b:
    m = len(b)
    chk = False
    for i in range(m-1, -1, -1):
        if b[i] == i + 1:
            ans.appendleft(b.pop(i))
            chk = True
            break
    if chk == False:
        print(-1)
        exit()
for x in ans:
    print(x)

Submission status: Accepted

Solution code:
n = int(input())
b = list(map(int,input().split()))
a = []
flag = 0

for i in range(n):
    tmp = []
    for j in range(len(b)):
        if j+1 == b[j]:
            tmp.append(b[j])
    if len(tmp) == 0:
        flag= 1
        break
    a.append(b.pop(tmp[-1]-1))

if flag == 0:
    for i in range(len(a)):
        print(a[-1-i])
else:
    print(-1)

Submission status: Accepted

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

ans = []
for i in range(N): # N回繰り返せば十分
    tgt = -1
    for i in reversed(range(len(B))):
        if B[i] == i+1:
            # B[i]をけす
            tgt = i
            break
    if tgt == -1:
        break
    ans.append(B[i])
    del B[i]

ans = ans[::-1]

if len(ans) == len(ORI_B):
    print('\n'.join(map(str, ans)))
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int,input().split()))
l = []
while b:
    for i in range(len(b)-1,-1,-1):
        if b[i] == i + 1:
            del b[i]
            l += i + 1,
            break
    else:
        print(-1)
        exit()
for i in l[::-1]:
    print(i)

Submission status: Accepted

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

res = []
for i in range(N):
    for j in range(N-i-1, -1, -1):
        if B[j] == j+1:
            res.append(j+1)
            B = B[:j]+B[j+1:]
            break
    else:
        break

if len(res) == N:
    res.reverse()
    for r in res:
        print(r)
else:
    print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, *b = map(int, open(0).read().split())
ans = []
for i in reversed(range(n)):
    for j in reversed(range(i + 1)):
        if b[j] == j + 1:
            ans.append(b.pop(j))
            break
    else:
        print(-1)
        exit()
print(*reversed(ans), sep="\n")

Submission status: Accepted

Solution code:
n, *b = map(int, open(0).read().split())
l = []
while 1:
    for i in reversed(range(len(b))):
        if i + 1 == b[i]:
            del b[i]
            l += i + 1,
            break
    else:
        break
if b:
    print(-1)
    exit()
for i in l[::-1]:
    print(i)

Submission status: Accepted

Solution code:
n=int(input())
b=list(map(int,input().split()))
ans=[]
for i in range(n):
  if b[i]-1>len(ans):
    print(-1)
    break
  else:
    ans.insert(b[i]-1,b[i])
else:
  for i in range(n):
    print(ans[i])

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int,input().split()))
c =[]
while b:
    a = 0
    for i in range(len(b)-1,-1,-1):
        if i+1 == b[i]:
            a = b.pop(i)
            c.append(a)
            break
    if a == 0:
        print(-1)
        exit()
for i in range(len(c)-1,-1,-1):
    print(c[i])

Submission status: Accepted

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

# In[10]:


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


# In[11]:


op = []
mylist = [x for x in b]
f = True
while len(mylist)>0:
    for i in reversed(range(len(mylist))):
        if mylist[i] == i+1:
            op.append(mylist.pop(i))
            break
    else:
        f = False
        break
if f:
    ans = list(reversed(op))
    for x in ans:
        print(x)
else:
    print(-1)


# In[ ]:

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
from collections import deque
from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations, islice
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    B = deque(LI())
    B.appendleft(0)
    # print(B)
    ans = deque([])
    for i in range(N, 0, -1):
        tmp = deque([])
        # print(B)
        for j in range(i, 0, -1):
            # print(i, j, B[j])
            if B[j] == j:
                # print(tmp)
                tmp2 = deque(islice(B, 0, j))
                tmp2.extend(tmp)
                # print(tmp2)
                # tmp2.appendleft(0)
                B = tmp2
                ans.appendleft(j)
                break
            else:
                tmp.appendleft(B[j])
        else:
            print(-1)
            return

    printlist(list(ans), '\n')

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(lambda x: int(x) - 1, input().split()))
res = []
for i in range(N):
    for j in range(len(B) - 1, -1, -1):
        if B[j] == j:
            res.append(B.pop(j))
            break
if len(B) == 0:
    for r in res[::-1]:
        print(r + 1)
else:
    print(-1)

Submission status: Accepted

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

ans = []

for i in range(n):
    tmp = -1
    for j,e in enumerate(b):
        if j + 1 == e:
            tmp = max(tmp, e)
    if tmp == -1:
        print(-1)
        exit()
    else:
        ans.append(tmp)
        b = b[:tmp-1] + b[tmp:]

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

Submission status: Accepted

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

res = []
for i in range(n):
    for j in range(len(b) - 1, -1, -1):
        if b[j] == j + 1:
            res.append(b.pop(j))
            break
    else:
        print('-1')
        exit()

for i in res[::-1]:
    print(i)

Submission status: Accepted

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

ans = []
for _ in range(n):
    for i, bi in enumerate(b[::-1]):
        i = len(b) - i
        if i == bi:
            ans.append(b.pop(i-1))
            break
print(*(ans[::-1] if len(ans) == n else[-1]), sep='\n')

Submission status: Accepted

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

ans = []
for _ in range(n):
    for i, bi in enumerate(b[::-1]):
        if len(b) == bi + i:
            ans.append(b.pop(len(b) - i - 1))
            break
print(*(ans[::-1] if len(ans) == n else [-1]), sep='\n')

Submission status: Accepted

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

a = []
flg = True
while b:
    for i in range(len(b), 0, -1):
        if b[i-1] == i:
            a.append(b.pop(i-1))
            break
        elif i == 1:
            flg = False
            break
    if not flg:
        break
a.reverse()
a = [str(i) for i in a]
print('\n'.join(a)) if flg else print(-1)

Submission status: Accepted

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

ans=[]
for i in range(n):
    for j in range(len(b)-1, -1, -1):
        if b[j]==j+1:
            ans.append(b.pop(j))
            break
ans=list(reversed(ans))

if len(ans)!=n:
    print(-1)
else:
    for ans_i in ans:
        print(ans_i)

Submission status: Accepted

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

out = []

for i in range(N):
    cand = []
    for j in range(len(B)):
        if B[j] == j + 1:
            cand.append(j)
    if len(cand) > 0:
        candmax = max(cand)
        out.append(candmax + 1)
        del B[candmax]
    else:
        print(-1)
        exit()
print(*out[::-1])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
enum = enumerate
INF = 1001001001

def linput(ty=int, cvt=list):
	return cvt(map(ty,input().rstrip().split()))

def vinput(rep=1, ty=int, cvt=list):
	return cvt(ty(input().rstrip()) for _ in "*"*rep)

def gcd(a: int, b: int):
	while b: a, b = b, a%b
	return a

def lcm(a: int, b: int):
	return a * b // gcd(a, b)

def main():
	N, = linput()
	vB = linput()
	
	vC = [b-i-1 for i,b in enum(vB)]
	vC.reverse()
	#print(N)
	res = 0
	vR = []
	
	for _ in "*"*N:
		try:
			x = vC.index(0)
			vR.append(vB[N-x-1])
			vC[x] = -INF
			for j in range(x):
				vC[j] += 1
		except ValueError as e:
			print(-1)
			return
	
	#sT = "No Yes".split()
	#print(sT[res])
	#print(res)
	print(*vR[::-1], sep="\n")

if __name__ == "__main__":
	main()

Submission status: Accepted

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

ans = []
while True:
    flag = False
    if len(b) == 0:
        break

    for i in range(len(b)):
        if i+1 == b[i]:
            idx = i
            flag = True
    if flag:
        tmp = b.pop(idx)
        ans.append(tmp)
    else:
        ans = [-1]
        break

print('\n'.join(map(str, reversed(ans))))

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
b_li = list(map(int, input().split()))
a_li = deque()
while len(b_li) > 0:
    found = False
    for i in range(len(b_li) - 1, -1, -1):
        if b_li[i] == i + 1:
            found = True
            a_li.appendleft(b_li[i])
            del b_li[i]
            break

    if not found:
        print(-1)
        exit()

for a in a_li:
    print(a)

Submission status: Accepted

Solution code:
n,*bb = map(int, open(0).read().split())

ans = []

while bb:
    imp = True
    for i,v in zip(range(len(bb),0,-1),bb[::-1]):
#         print(i,v)
        if i==v:
            ans.append(v)
            del bb[i-1]
            imp = False
            break
    if imp:
        ans = [-1]
        break

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
"""
def main():
    N = int(input())
    b_lsit = list(map(int, input().split()))

    flag = True
    answer_list = []
    while flag and b_lsit:
        #print(b_lsit)
        for i in range(len(b_lsit)-1, -2, -1):
            if i == -1:
                flag = False
                break
            elif b_lsit[i] == i+1:
                answer_list.append(b_lsit.pop(i))
                break

    if flag:
        for b in answer_list[::-1]:
            print(b)
    else:
        print(-1)

    return

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict
from math import sqrt, factorial, gcd, ceil
# def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('utf-8')
import string
# string.ascii_lowercase
from bisect import bisect_left

def solve():
    n = int(input())
    ans = [0] * n
    a = [int(x) for x in input().split()]
    ok = 1
    cur = n - 1
    while ok and a:
        ok = 0
        i = len(a) - 1
        while i >= 0:
            if a[i] - 1 == i:
                ok = a[i]
                a.pop(i)
                break
            i -= 1
        ans[cur] = ok
        cur -= 1

    if a:
        print(-1)
    else:
        for e in ans:
            print(e)
t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()


"""

azyxwvutsrqponmlkjihgfedcb

"""

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(int, input().split()))
B = [0] + B


ANS = []
flag = 0
while B != [0]:
    for j in range(len(B)-1, 0, -1):
        b = B[j]
        if b == j:
            ANS.append(B.pop(j))
            break
    else:
        flag = 1
        break
        
if flag:
    print(-1)
else:
    for ans in ANS[::-1]:
        print(ans)

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N = I()
    b = LI()

    # bから数字を除去して空にできるか判定する
    ans = []
    while b:
        has_pop = False
        len_b = len(b)
        for i in range(len_b):
            j = len_b - 1 - i
            if b[j] == j + 1:
                b.pop(j)
                ans.append(j + 1)
                has_pop = True
                break
        if not has_pop:
            break

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

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n, s = open(0)
a=['']
for i in s.split():
    a.insert(int(i)-1, i)
if a[-1] == "":
    print(*a)
else:
    print(-1)

Submission status: Accepted

Solution code:
N=int(input())
l=list(map(int,input().split()))
ans=[]
for i in range(N):
   for j in reversed(range(N-i)):
      if j+1 == l[j]:
         ans.append(l[j])
         l.pop(j)
         break
      if j == 0:
         print("-1")
         exit()
ans=ans[::-1]
for i in ans:
   print(i)

Submission status: Accepted

Solution code:
N = int(input())
DUMMY = -1
B = [DUMMY] + list(map(int, input().split()))

# 右から見ていって正しい位置にある数字が最後に挿入したもの
def last_insert_elem():
    for b,i in zip(reversed(B), reversed(range(len(B)))):
        if b==i:
            return B.pop(i)
    return DUMMY

ans = []
for _ in range(N):
    e = last_insert_elem()
    if e == -1:
        print(-1)
        exit()
        
    ans.append(e)

print(*reversed(ans), sep='\n')

Submission status: Accepted

Solution code:
n=int(input())
b=list(map(int,input().split()))
ans=[]
for i in range(n):
    t=1
    tmp=0
    for j in range(len(b)):
        if b[t-1]==t:
            tmp=t
        t+=1
    if tmp==0:
        print(-1)
        exit()
    else:
        ans.append(b.pop(tmp-1))
        
if b:
    print(-1)
else:
    print(*ans[::-1])

Submission status: Accepted

Solution code:
N=int(input())
b=list(map(int, input().split()))
ans=[]
for i in range(N):
  for j in range(len(b)-1, -1, -1):
    if b[j]==j+1:
      ans.append(b.pop(j))
      break
      
if len(ans)<N:
  print(-1)
else:
  for i in range(N-1, -1, -1):
    print(ans[i])

Submission status: Accepted

Solution code:
n = int(input())
B = list(map(lambda x: x-1, map(int, input().split())))
ans = []
for i in range(n):
    for j in range(len(B)-1,-1,-1):
        if B[j]==j:
            ans.append(j+1)
            del B[j]
            break
        elif j==0:
            ans = -1
            break
    if ans==-1:
        break

if ans == -1:
    print(ans)
else:
    for _ans in ans[::-1]:
        print(_ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/agc032/tasks/agc032_a
import sys

n = int(input())
nums = [int(i) - 1 for i in input().split()]
ans = []
for i in range(n):
    for j in range(len(nums) - 1, -1, -1):
        if nums[j] == j:
            ans.append(j + 1)
            del nums[j]
            break
    else:
        print(-1)
        sys.exit()
for a in ans[::-1]:
    print(a)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, b: "List[int]"):
    c = b[:] # debug
    ans = []
    while c:
        x = max(filter(lambda x: x[0] == x[1], enumerate(c, 1)), default=0)
        if not x:
            return [-1]
        ans.append(x[0])
        del c[x[0]-1]
    return ans[::-1]

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    b = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    print(*solve(N, b), sep="\n")

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Accepted

Solution code:
n = int(input())
b = list(map(int, input().split()))
ans = []
for i in range(n, 0, -1):
    ok = False
    for j in range(i, 0, -1):
        if b[j - 1] == j:
            ans.append(b.pop(j - 1))
            ok = True
            break
    if not ok:
        print(-1)
        exit()

for i in range(n):
    print(ans.pop())

Submission status: Accepted

Solution code:
from collections import deque

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

result = deque([])
while b:
    for i in range(len(b) - 1, -1, -1):
        if b[i] == i + 1:
            result.appendleft(b.pop(i))
            break
    else:
        break

if not b:
    #print('\n'.join(str(i) for i in result))
    print(*result, sep='\n')
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque

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

result = deque([])
while b:
    for i in range(len(b) - 1, -1, -1):
        if b[i] == i + 1:
            result.appendleft(b.pop(i))
            break
    else:
        break

if not b:
    print('\n'.join(str(i) for i in result))
    #print(*result, sep='\n')
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

#i がi番以降にあるなら可能
N = INT()
a = LIST()

ans = deque()
while a:
	for i in range(len(a)-1, -1, -1):
		if a[i] == i+1:
			ans.appendleft(a.pop(i))
			break
	else:
		print(-1)
		exit()

print(*ans, sep="\n")

Submission status: Accepted

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

ans = []
while N > 0:
  ok = False
  for i in range(N)[::-1]:
    b = B[i]
    if b == (i+1):
      ans.append(b)
      ok = True
      k = i
      break
  
  if not ok:
    break
  else:
    newB = []
    for i in range(N):
      if i != k:
        newB.append(B[i])
    
    B = newB
    N -= 1

if N != 0:
  print(-1)
else:
  print("\n".join(map(str,ans[::-1])))

Submission status: Accepted

Solution code:
n = int(input())
b = list(map(int, input().split()))
a = []
while n > 0:
    x = -1
    for i in range(n):
        if b[i] == i + 1:
            x = i
    if not x == -1:
        b.pop(x)
        a.append(x + 1)
    else:
        print(-1)
        exit()
    n -= 1
a.reverse()
for i in a:
    print(i)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
b = list(map(int, input().split()))
ans = []
for i in range(n):
    target = None
    for j in range(n-i):
        if int(b[j])==j+1:
            target = j
    if target is None:
        ans = -1
        break
    ans.append(target+1)
    b = b[:target] + b[target+1:]
else:
    ans = "\n".join(map(str, ans[::-1]))
print(ans)

Submission status: Accepted

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

for i in range(n):
    if i+1<b[i]:
        print(-1)
        exit(0)


from collections import deque

d=deque([])

while len(d)<n:
    tmp=b
    for j in range(len(tmp)-1,-1,-1):
        if j+1==tmp[j]:
            d.append(tmp[j])
            break

    b.pop(j)


for _ in range(n):
    v=d.pop()
    print(v)

Submission status: Accepted

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

ans = []
while B:
    for i,v in enumerate(B[::-1]):
        if len(B)-i == v:
            a = B.pop(len(B)-i-1)
            ans.append(a)
            break
    else:
        break
if not B:
    print(*ans[::-1],sep='\n')
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    B = list(map(int, input().split()))

    res = []
    while B:
        for i in reversed(range(len(B))):
            if B[i] == i + 1:
                b = B.pop(i)
                res.append(b)
                break
        else:
            print(-1)
            exit()
    print(*res[::-1], sep="\n")


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n=int(input())
b=list(map(int,input().split()))
ans=[]
while True:
    l=len(b)
    temp=[]
    flag=0
    for i in range(l-1,-1,-1):
        if flag==1 or b[i]!=i+1: temp.append(b[i])
        else:
            ans.append(i+1)
            flag=1
    b=temp[::-1]
    if len(b)==l:
        print(-1)
        exit()
    elif len(b)==0: break
for val in ans[::-1]: print(val)

Submission status: Accepted

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

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

ans = []
while len(l) > 0:
    for i, x in enumerate(l[::-1]):
        if len(l) - i == x:
            ans.append(x)
            l.pop(len(l)-i-1)
            break
for i, x in enumerate(ans[::-1]):
    print(x)

Submission status: Accepted

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

ans = []

while b:
    f = True
    for i in range(len(b)-1, -1, -1):
        if b[i] == i+1:
            b.remove(i+1)
            ans.append(i+1)
            f = False
            break
    if f: # 実行できない
        ans = '-1'
        break
if ans == '-1':
    print(ans)
else:
    for a in ans[::-1]:
        print(a)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():

    N = in_n()
    b = in_nl()

    ans = []
    while True:
        ind = -1
        for i in range(len(b)):
            if i+1 == b[i]:
                ind = i
        if ind != -1:
            b.pop(ind)
            ans.append(ind+1)
            if len(b) == 0:
                break
        else:
            break

    if len(b) == 0:    
        print('\n'.join(map(str, (ans[::-1]))))
    else:
        print(-1)





if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from copy import deepcopy
N = int(input())
b = [int(i) for i in input().split()]

ans = []
for i, x in enumerate(b):
    if x > i+1:
        print(-1)
        sys.exit()
while len(b) != 0:
    for i, x in enumerate(b[::-1]):
        if len(b)-i == x:
            ans.append(x)
            b.pop(len(b) - i - 1)
            break
print(*ans[::-1], sep='\n')

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul

INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 組合せnCr
def combinations_count(n, r):
    if n < r:
        return 0
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
n = int(input())
b = list(map(int, input().split()))

x = [0 for i in range(n)]
ans = []
while True:
    flag = True
    for i in reversed(range(n)):
        if x[i] > 0:
            continue
        cnt = sum(x[:i])
        # for j in reversed(range(i)):
        #     if x[j] > 0:
        #         cnt += 1
        if b[i] == cnt + 1:
            x[i] = 1
            ans.append(b[i])
            flag = False
            break
    if len(ans) == n:
        break
    if flag:
        break

# print("ans =", ans)
if len(ans) < n:
    print(-1)
else:
    for i in ans:
        print(i)

Submission status: Accepted

Solution code:
N = int(input())
B = list(map(lambda x: int(x)-1, input().split()))

ans = []
for i in range(N):
    erase = -1
    for c in reversed(range(len(B))):
        if B[c] == c:
            erase = c
            break
    
    if erase == -1:
        print(-1)
        exit()
    else:
        ans.append(erase)
        B.pop(erase)

for _ in ans[::-1]:
    print(_+1)

Submission status: Accepted

Solution code:
N = int(input())
b = list(map(int, input().split()))
for i in range(N):
    b[i] -= 1
lis = []
for i in range(N):
    flg = False
    for j in reversed(range(N-i)):
        if b[j] == j:
            lis.append(j+1)
            del b[j]
            flg = True
            break
    if flg == False:
        print(-1)
        exit()
for i in reversed(range(N)):
    print(lis[i])