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: Wrong Answer

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

A = []
for i in range(1,N+1):
  for b in B:
    if(B == []):
      exit()
    if(1 <= b <= i):
      A.insert(b-1, b)
      tmp = b
      B.remove(b)
      break
if(B == []):
  for a in A:
    print(a)
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
for i in input().split():
  print(i)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int,input().split()))
A = sorted(A)
D = {}
for i in range(1,101) :
    D[i] = A.count(i)
flg = 0
for i in range(1,len(A)+1) :
    if A[i-1] > i :
        print(-1)
        flg = 1
        break
L = []
if flg == 0 :
    L = []
    for i in range(1,101) :
        L.extend([i for j in range(D.get(i,1)-1)])
    for i in range(100,0,-1) :
        if D[i] != 0 :
            L.append(i)
    print(*L[::-1],sep="\n")

Submission status: Wrong Answer

Solution code:
n = int(input())
b = [int(i) for i  in input().split()]
import collections
if b[0] == 1:
    diff = [abs(b[i+1] - b[i]) for i in range(len(b)-1)]
    c = collections.Counter(diff)
    if len(set(c.keys()) - {0,1}) == 0:
        a = "".join([str(i) for i in b]).split("1")
        a = [list(("1" + i)) for i in a[1:]]
        ans = []
        for i in range(len(a)-1, -1, -1):
            tmp = [int(j) for j in a[i]]
            ans.extend(sorted(tmp))
        for i in ans:
            print(i)
    else:
        print(-1)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
n=int(input())
l=list(map(int,input().split()))
l.reverse()
l2=[]
l3=[]
for x in l:
  if x==1:
    l2.append(x)
    l2.sort()
    l3+=l2
    l2=[]
  else:
    l2.append(x)
if n!=len(l3):
  print(-1)
  exit()
for x in l3:
  print(x)

Submission status: Wrong Answer

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

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

for i in range(N):
    print(str(b[i]))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
b = [int(i) for i in input().split()]
count = 0
for i in range(N):
    if b[i] > i+1:
        count += 1
if count >= 1:
    print(-1)
else:
    for i in b:
        print(i)

Submission status: Wrong Answer

Solution code:
n = int(input())
b = map(int, input().split())
a = [range(1, _n + 1) for _n in range(1, n + 1)]

for i, _b in enumerate(b):
    if _b in a[i]:
        print(_b)
    else:
        print(-1)
        break

Submission status: Wrong Answer

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

b=sorted(b)
for i in range(n):
    if not b[i]<=i+1:
        print(-1)
        break
        
print(b)

Submission status: Wrong Answer

Solution code:
n = int(input())
li = list(map(int, input().split()))
li.sort()
test = True
for i in range(n):
    if i + 1 <  li[i]:
        test = False
        break

if(test):
    for el in li:
        print(el)
else:
    print(-1)

Submission status: Wrong Answer

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

b = sorted(b)
flag = True

for i in range(n):
    a.append(b[i])
    if b[i] > i+1:
        flag = False

if flag == False:
    print("-1")

else:
    for i in a:
        print(i)

Submission status: Wrong Answer

Solution code:
N = int(input())
b = input().split()
b = [int(x) for x in b]
a = []

for i in range(N):
  if b[i] >= 1 and b[i] <= i + 1:
    a.append(b[i])
  else:
    print(-1)
    exit
print(a)

Submission status: Wrong Answer

Solution code:
x = int(raw_input())
l =  map(int, raw_input().split())
l.sort()
control = True
t = []

for k in xrange(x):
	if l[k] <= k + 1:
		t.append(str(l[k]))
		
	else:
		control = False
		
if control:
	print "\n".join(t)
else:
	print -1

Submission status: Wrong Answer

Solution code:
def solve():
  N = int(input())
  B = [int(i) for i in input().split()]
  ans = [' '] * N

  for i in range(N - 1, -1, -1):
    flag = False
    for j in range(len(B)):
      if B[j] == j + 1: continue
      if j == 0: return '-1'
      flag = True
      ans[i] = str(B.pop(j - 1))
      break
    if not flag: ans[i] = str(B.pop(-1))

  return '\n'.join(ans)

print(solve())

Submission status: Wrong Answer

Solution code:
N = int(input())
tmp = input().split()
b = []

for i in range(N):
  b.append(tmp[i])

for index, item in enumerate(b):
  if int(item) > index+1:
    print('-1')
    exit()

idx_top = 0
idx_bottom = len(b)-1

print(b[idx_top])
idx_top += 1

for i in range(len(b)-1):
  if b[idx_top] >= b[idx_bottom]:
    print(b[idx_top])
    if idx_top < idx_bottom:
      idx_top += 1
  else:
    print(b[idx_bottom])
    if idx_bottom > idx_top:
      idx_bottom -= 1

Submission status: Wrong Answer

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

B=sorted(B)


for n in range(N):
	if n+1 < B[n]:
		print(-1)
		exit()

for n in range(N):
	print(B[n])

Submission status: Wrong Answer

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

b=sorted(b)
for i in range(n):
    if b[i]<=i+1:
        print(b[i])
    else:
        print(-1)
        break

Submission status: Wrong Answer

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

for n in range(N):
	if n+1 < B[n]:
		print(-1)
		exit()

for n in range(N):
	print(B[n])

Submission status: Wrong Answer

Solution code:
n = int(input())
list = list(map(int,input().split()))
list.sort()
flag = 0
for i in range(n):
  if list[i] > i+1:
    flag = 1
    break;
if flag == 1:
  print("-1")
else:
  for j in range(n):
    print(list[j])

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int,input().split()))
A = sorted(A)
D = {}
for i in range(1,101) :
    D[i] = A.count(i)

for i in range(1,len(A)+1) :
    if A[i-1] > i :
        print(-1)
        break
else :
    print(*A,sep="\n")

Submission status: Wrong Answer

Solution code:
N = int(input())
b = list(map(int,input().split()))
b = sorted(b)
tmp = list(range(1,N+1))
ans = [x - y for (x, y) in zip(tmp, b)]
if min(ans) >= 0:
  for i in range(N):
    print(b[i])
else:
  print('-1')

Submission status: Wrong Answer

Solution code:
N=int(input())
hoge=list(map(int,input().split()))
hoge.sort()
flag=0
for i in range(N):
  if(hoge[i]>i+1):
    flag=1
    
if(flag==0):
  for i in range(N):
  	print(hoge[i])
else:
  print(-1)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

ans = []

for i in range(N):
    print(c[i])
# c = c[::-1]
# for i in range(N):
#     for j in range(len(b)):
#         if b[j] == c[i]:
#             b.pop(j)
#             ans.append(j + 1)
#             break

# ans = ans[::-1]
# for i in range(N):
#     print(ans[i])

Submission status: Wrong Answer

Solution code:
N=int(input())
hoge=list(map(int,input().split()))
hoge.sort()
flag=0
for i in range(N):
  if(hoge[i]>i+1):
    flag=1
    
if(flag==0):
  for i in range(N):
  	print(hoge[i],end=" ")
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
n=int(input())
x=list(map(int,input().split()))
x=sorted(x)
for i, a in enumerate(x):
    if a > i+1:
        print(-1)
        break
else:
    for i in x:
        print(i)

Submission status: Wrong Answer

Solution code:
from sys import exit
N = int(input())
B = list(map(int, input().split()))
ctr = 0
ans = []
for _ in range(N):
    for i, b in enumerate(B, 1):
        if i == b:
            ctr = i
    ans.append(ctr)
    if ctr == 0:
        print(-1)
        exit()
    B = B[:ctr-1] + B[ctr:]
print('\n'.join([str(s) for s in ans][::-1]))

Submission status: Wrong Answer

Solution code:
N = int(input())
b = list(map(int, input().split()))
b.sort()
if all(b.count(i) <= N-i +1 for i in range(1, N+1)):
    for num in b:
        print(num)
else:
    print("-1")

Submission status: Wrong Answer

Solution code:
N = int(input())
b = list(map(int, input().split()))
if b[0] > 1:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter


def input():
    return sys.stdin.readline().strip()
# sys.setrecursionlimit(100000)


def helper(cur: list, B, candi, ans, rest):
    if rest == 0:
        if cur == B:
            for i in ans:
                print(i)
            sys.exit()
        else:
            return
    for k, v in candi.items():
        if v > 0 and len(cur) + 1 >= k:
            cur.insert(k - 1, k)

            candi[k] -= 1
            helper(cur, B, candi, ans + [k], rest - 1)
            cur.pop(k - 1)
            candi[k] += 1


def main():
    n = int(input().strip())
    B = [int(i) for i in input().strip().split()]
    counter = Counter(B)
    helper([], B, counter, [], n)
    print(-1)
    return


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def check_val(ind):
    if ind > len(b): return False 
    if b[ind-1] == ind:
        ans.append(ind)
        del b[ind-1]
        return True
    else:
        return False


N,*b = map(int,open(0).read().split())
if b[0] != 1: 
    print(-1)
    exit()

set_b = sorted(set(b),reverse=True)
ans = []
while len(b) != 0:
    flg = False
    for i in set_b:
        flg = check_val(i)
        if flg: break
    if set_b[-1] not in b: del set_b[-1]
else: #消せるものがなくなった
    if len(b) == 0:
        print(*ans[::-1],sep="\n")
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
def check_val(ind):
    if ind > len(b): return False 
    if b[ind-1] == ind:
        ans.append(ind)
        del b[ind-1]
        return True
    else:
        return False


N,*b = map(int,open(0).read().split())
if b[0] != 1: 
    print(-1)
    exit()

set_b = sorted(set(b),reverse=True)
ans = []
while len(b) != 0:
    flg = False
    for i in set_b:
        flg = check_val(i)
        if flg: break
else: #消せるものがなくなった
    if len(b) == 0:
        print(*ans[::-1],sep="\n")
    else:
        print(-1)

Submission status: Time Limit Exceeded

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

ans = []

while bb:
    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]
            break

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce, lru_cache  # @lru_cache(None)
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return (int(x) for x in input().split())
def LI(): return list(Is())
def TI(): return tuple(Is())
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(S())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18
# ----------------------------------------------------------- #

n = I()
B = LI()
ANS = []
def dfs(C, D):
    global ANS
    if len(D) == 0:
        ANS = reversed(C)
    for i, d in enumerate(D):
        if i+1 == d:
            if i == len(D)-1:
                dfs(C+[d], D[:i])
            else:
                dfs(C+[d], D[:i]+D[i+1:])
dfs([], B)
if not ANS:
    print(-1)
    exit()
for ans in ANS:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


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

def main():
    def dfs(vec):
        i = 0
        zero_only = True
        for j in range(len(vec)):
            if vec[j] > 0:
                zero_only = False
                i += 1
                if vec[j] == i:
                    vec[j] = 0
                    ret = dfs(vec)
                    vec[j] = i
                    if ret != False:
                        ret.append(i)
                        return ret
        if zero_only:
            return []
        else:
            return False

    ans = dfs(B)
    if ans == False:
        print(-1)
    else:
        print(*ans, sep='\n')

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


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


def dfs(vec):
    i = 0
    zero_only = True
    for j in range(len(vec)):
        if vec[j] > 0:
            zero_only = False
            i += 1
            if vec[j] == i:
                vec[j] = 0
                ret = dfs(vec)
                vec[j] = i
                if ret != False:
                    ret.append(i)
                    return ret
    if zero_only:
        return []
    else:
        return False


ans = dfs(B)
if ans == False:
    print(-1)
else:
    print(*ans, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)

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

def dfs(s, ans):
    #print(s, ans)
    if len(s) == 0:
        print('\n'.join(map(str, reversed(ans))))
        exit()
        return
    for i in range(len(s)):
        if s[i] == i+1:
            s1 = s[:i] + s[i+1:]
            ans.append(s[i])
            dfs(s1, ans)
    if len(ans) > 0:
        ans.pop()

dfs(b, [])

print('-1')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float('inf')
MOD=10**9+7
input=sys.stdin.readline

n=int(input())
s=list(map(int,input().split()))
import copy
def DEF(ary,ary2):
    #print(ary,ary2)
    global n,s
    if len(ary2)==n:
        #print(ary)
        if ary==s:
            for item in ary2:
                print(item)
            exit()
    else:
        for i in range(len(ary)+1):
            tmp = copy.deepcopy(ary)
            tmp.insert(i,i+1)
            DEF(tmp,ary2+[i+1])

DEF([],[])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import sys
sys.setrecursionlimit(10**7)
n = int(input())
B = list(map(int, input().split()))
c = Counter(B)
A = []
history = []


def dfs(i):
    if i == n+1:
        if A == B:
            print(*history, sep='\n')
            exit()
        return 0
    for j in reversed(range(1, i+1)):
        if not c[j]:
            continue
        c[j] -= 1
        history.append(j)
        A.insert(j-1, j)
        dfs(i+1)
        A.pop(j-1)
        history.pop()
        c[j] += 1


dfs(1)
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import sys
sys.setrecursionlimit(10**7)
n = int(input())
B = list(map(int, input().split()))
c = Counter(B)
A = []
ans = -1
history = []


def dfs(i):
    if i == n+1:
        if A == B:
            global ans
            ans = history[::]
        return 0
    for j in range(1, i+1):
        if not c[j]:
            continue
        c[j] -= 1
        history.append(j)
        A.insert(j-1, j)
        dfs(i+1)
        A.pop(j-1)
        history.pop()
        c[j] += 1


dfs(1)
if ans == -1:
    print(ans)
else:
    print(*ans, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline  # NOQA
sys.setrecursionlimit(10 ** 7)  # NOQA


def dfs(N, a, i, b, procedure):
    if i == 0:
        return procedure

    for j in range(1, i+1):
        if a[j-1] == j:
            l = a[:]
            del l[j-1]
            p = procedure[:]
            p.append(j)
            ret = dfs(N, l, i-1, b, p)
            if ret is not None:
                return ret


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

    res = dfs(N, b, N, b, [])
    if res is None:
        print(-1)
    else:
        print(*res[::-1], sep="\n")


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def solve(remains, nums):
    if (len(remains)) == 0:
        [print(num) for num in nums[::-1]]
        exit()
    n_remains = []
    n_nums = []
    for i, num in enumerate(remains):
        if i + 1 == num:
            n_remains.append(remains[:i] + remains[i + 1:])
            n_nums.append(nums + [i + 1])
    if len(n_remains) == 0:
        return False
    for n_remain, n_num in zip(n_remains, n_nums):
        solve(n_remain, n_num)


n = int(input())
B = [int(x) for x in input().split()]

solve(B, [])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
B=list(map(int,input().split(' ')))
def dfs(n,B,ans):
    if n==0:
        return ans[::-1]
    else:
        for num,i in enumerate(B):
            if num+1==i:
                res = dfs(n-1,B[:num]+B[num+1:],ans+[i])
                if res:
                    return res
        return False
ans = dfs(N,B,[])
if not ans:
    print(-1)
else:
    for i in ans:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
B=list(map(int,input().split(' ')))
def dfs(n,B,ans):
    if n==0:
        return ans[::-1]
    else:
        for num,i in enumerate(B):
            if num+1==i and dfs(n-1,B[:num]+B[num+1:],ans+[i]):
                return dfs(n-1,B[:num]+B[num+1:],ans+[i])
        return False
ans = dfs(N,B,[])
if not ans:
    print(-1)
else:
    for i in ans:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
from itertools import permutations

mod = 10**9 + 7

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))

n = ni()
b = na()

for p in permutations(b):
    a = list()
    for i in range(1, n+1):
        if p[i-1] > i:
            break
        else:
            if p[i-1] == i:
                a.append(p[i-1])
            elif p[i-1] == 1:
                a = [1] + a
            else:
                a = a[:p[i-1]-1] + [p[i-1]] + a[p[i-1]-1:]
            #print(i, p[i-1], a)
        if a == b:
            for i in range(1, n+1):
                print(p[i-1])
            quit()
print(-1)

Submission status: Time Limit Exceeded

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

def solve(l, ans):
	if l == []:
		return ans

	cnd = [] 
	for i in range(len(l)):
		if l[i] == i+1:
			cnd.append(i)

	if cnd == []:
		return 0

	for ind in cnd:
		ans.append(ind+1)
		cond = solve(l[0:ind] + l[(ind+1):(len(l)+1)], ans)
		if cond == 0:
			ans.pop()
			continue
		else:
			return cond


	return 0	

ans = solve(a,[])

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

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)

ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))  # applies to only numbers
rs = lambda: stdin.readline().rstrip()  # ignores trailing space

N = ri()
B = rl()
l = []
for i in range(N):
    if i + 1 < B[i]:
        print(-1)
        exit()

while B:
    for i in range(len(B)-1, -1, -1):
        while True:
            if i + 1 == B[i]:
                if i == len(B)-1:
                    l.append(B.pop(i))
                    break
                elif B[i+1] <= i+1:
                    l.append(B.pop(i))
                else:
                    break
            else:
                break

l = l[::-1]
print(*l, sep='\n')
# 47

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

N = int(input())

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

q = deque([])

q.append([b,[]])

dic = {}

while len(q) > 0:

    now = q.pop()

    nb = now[0]
    nc = now[1]

    for i in range(len(nb)):

        if (i+1) == nb[i]:

            nex = []
            nec = []
            for j in range(len(nb)):
                if j != i:
                    nex.append(nb[j])
            for j in range(len(nc)):
                nec.append(nc[j])
            
            nec.append(nb[i])
            

            s = " ".join(map(str,nex))
            if s in dic:
                continue
            dic[s] = 1

            if len(nex) == 0:
                nec.reverse()
                print (" ".join(map(str,nec)))
                sys.exit()

            q.append([nex,nec])

print (-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

N = int(input())

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

q = deque([])

q.append([b,[]])

dic = {}

while len(q) > 0:

    now = q.pop()

    nb = now[0]
    nc = now[1]

    for i in range(len(nb)):

        if (i+1) == nb[i]:

            nex = nb.copy()
            nec = nc.copy()
            
            nec.append(nex[i])
            del nex[i]

            s = " ".join(map(str,nex))
            if s in dic:
                continue
            dic[s] = 1

            if len(nex) == 0:
                nec.reverse()
                print (" ".join(map(str,nec)))
                sys.exit()

            q.append([nex,nec])

print (-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

N = int(input())

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

q = deque([])

q.append([b,[]])

while len(q) > 0:

    now = q.pop()

    nb = now[0]
    nc = now[1]

    for i in range(len(nb)):

        if (i+1) == nb[i]:

            nex = nb.copy()
            nec = nc.copy()
            nec.append(nex[i])
            del nex[i]

            if len(nex) == 0:
                nec.reverse()
                print (" ".join(map(str,nec)))
                sys.exit()

            q.append([nex,nec])

print (-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

N = int(input())

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

q = deque([])

q.append([b,[]])

while len(q) > 0:

    now = q.popleft()

    nb = now[0]
    nc = now[1]

    for i in range(len(nb)):

        if (i+1) == nb[i]:

            nex = nb.copy()
            nec = nc.copy()
            nec.append(nex[i])
            del nex[i]

            if len(nex) == 0:
                nec.reverse()
                print (" ".join(map(str,nec)))
                sys.exit()

            q.append([nex,nec])

print (-1)

Submission status: Time Limit Exceeded

Solution code:
LIST=""
LIST=list(LIST)
c=0

def func(S):
    global LIST
    global c

    if(len(S)==0):
        c=1
    if(c==1):
        for i in range(len(LIST)-1,-1,-1):
            print(LIST[i])
        exit()

    So=S[::]
    for i in range(len(S)):
        S=So[::]
        if(S[i]==(i+1)):
            LIST.append(S.pop(i))
            func(S)
    if(len(LIST)==0):
        print("-1")
        exit()
    LIST.pop(-1)

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

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

func(S)
print("-1")

Submission status: Time Limit Exceeded

Solution code:
LIST=""
LIST=list(LIST)
c=0

def func(S):
    global LIST
    global c

    if(len(S)==0):
        c=1
    if(c==1):
        for i in range(len(LIST)-1,-1,-1):
            print(LIST[i])
        exit()

    So=S[::]
    for i in range(len(S)):
        S=So[::]
        if(S[i]==(i+1)):
            LIST.append(S.pop(i))
            func(S)
    if(len(LIST)==0):
        print("-1")
        exit()
    LIST.pop(-1)

N=int(input())
S=list(map(int,input().split()))
func(S)
print("-1")

Submission status: Time Limit Exceeded

Solution code:
LIST=""
LIST=list(LIST)
c=0

def func(S):
    global LIST
    global c

    if(len(S)==0):
        c=1
    if(c==1):
        for i in range(len(LIST)-1,-1,-1):
            print(LIST[i])
        exit()

    So=S[::]
    for i in range(len(S)):
        S=So[::]
        if(S[i]==(i+1)):
            LIST.append(S.pop(i))
            func(S)
    if(len(LIST)>0):
        LIST.pop(-1)

N=int(input())
S=list(map(int,input().split()))
func(S)
print("-1")

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys

sys.setrecursionlimit(200000000)

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

def dfs(string, root):
    temps = [i+1 for i in range(len(string))]
    output=-1
    if len(string)==0:
        return root
    
    for i,s in enumerate(string):
        if i+1==s:
            temp_root = copy.deepcopy(root)
            temp_string=copy.deepcopy(string)
            temp_root.append(i+1)
            temp_string.pop(i)
            temp = dfs(temp_string, temp_root)
            
            if temp!=-1:
                output=temp
                break
    return output

output=dfs(a, [])

output

if isinstance(output, list):
    for i in output[::-1]:
        print(i)
else:
    print(output)

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys

sys.setrecursionlimit(200000000)

N=int(input())
a = list(map(int,input().split()))
values = set(a)

dicts={}
def dfs(string, root):
    temps = [i+1 for i in range(len(string))]
    output=-1
    if len(string)==0:
        return root
    
    for i,s in enumerate(string):
        if i+1==s:
            temp_root = copy.deepcopy(root)
            temp_string=copy.deepcopy(string)
            temp_root.append(i+1)
            temp_string.pop(i)
            temp = dfs(temp_string, temp_root)
            
            if temp!=-1:
                output=temp
    return output

output=dfs(a, [])

output

if isinstance(output, list):
    for i in output[::-1]:
        print(i)
else:
    print(output)

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys

sys.setrecursionlimit(200000000)

N=int(input())
a = list(map(int,input().split()))
values = set(a)

dicts={}
def dfs(index, string, values, N, root):
    temp=[]
    if index == N:
        dicts[" ".join(list(map(str,string)))] = root
        return None
    
    length = len(string)+1
    
    for i in values:

        if i > index:
            break
        temp_str = copy.deepcopy(string)
        temp_root = copy.deepcopy(root)
        temp_str.insert(i-1,i)
        temp_root.append(i)
        
        dfs(index+1, temp_str, values, N, temp_root)
        

        

dfs(1,[], values, N+1, [])

output = " ".join(list(map(str,a)))

if output in dicts:
    for i in dicts[output]:
        print(i)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque

N = int(stdin.readline().rstrip())
b = [int(x) for x in stdin.readline().rstrip().split()]
ans = deque([])

while N > 0:
    index = N - 1
    while index >= 0:
        if b[index] == index + 1:
            ans.appendleft(b[index])
            b1 = b[:index]
            b2 = b[index + 1:]
            b = b1 + b2
            N -= 1
            break
        index -= 1

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque

N = int(stdin.readline().rstrip())
b = [int(x) for x in stdin.readline().rstrip().split()]
ans = deque([])

while len(b) > 0:
    index = len(b) - 1
    while index >= 0:
        if b[index] == index + 1:
            c = b.pop(index)
            ans.appendleft(c)
            break
        index -= 1

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
from collections import defaultdict, deque
import math
from math import factorial
import re

def is_subseq(a, b):
    if not a:
        return True
    try:
        index = b.index(a[0])
        return is_subseq(a[1:], b[index+1:])
    except:
        return False

def bfs(a, b, hist, bcounter):
    if not is_subseq(a, b):
        return None
    if tuple(a) == tuple(b):
        return hist

    i = len(hist) + 1
    candidates = [j for j in bcounter if j <= i]
    for j in candidates:
        new_a = list(a) 
        new_a.insert(j-1, j)
        new_bcounter = dict(bcounter)
        new_bcounter[j] -= 1
        if new_bcounter[j] == 0:
            del new_bcounter[j]
        res = bfs(new_a, b, hist + [j], new_bcounter)
        if res:
            return res
    return None

def main():
    #N, K = map(int, input().split())
    N = int(input())
    b = list(map(int, input().split()))

    assert is_subseq([1, 2], [3, 1, 4, 2])
    assert is_subseq([1, 2, 1], [3, 1, 4, 2, 1])
    assert not is_subseq([1, 2, 1], [3, 1, 4, 2])

    bcounter = defaultdict(int)
    for x in b:
        bcounter[x] += 1

    res = bfs([], b, [], bcounter)
    if res:
        for r in res:
            print(r)
    else:
        print("-1")

if __name__ == '__main__':
    main()