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: 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):
    if not is_subseq(a, b):
        return None
    if tuple(a) == tuple(b):
        return hist
    if len(hist) > len(b):
        raise Exception("Error")
    i = len(hist) + 1
    for j in range(1, i+1):
        new_a = list(a) 
        new_a.insert(j-1, j)
        res = bfs(new_a, b, hist + [j])
        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])

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

ans = []  
 
def check(bs, pre):
  tmp = pre[:]
  if len(bs) == 0:
    ans.append(tmp)
    return
  cand = []
  for i, b in enumerate(bs):
    if i + 1 == b:
      cand.append(i)
  if len(cand) == 0:
    return
  for i in cand:
    check(bs[:i] + bs[i+1:], [i + 1] + tmp)

check(bs, [])

if len(ans):
  for ai in ans[0]:
    print(ai)
else:
  print(-1)

Submission status: Time Limit Exceeded

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

ans = []  
 
def check(bs, pre):
  tmp = pre[:]
  if len(bs) == 0:
    ans.append(tmp)
    return
  cand = []
  for i, b in enumerate(bs):
    if i + 1 == b:
      cand.append(i)
  if len(cand) == 0:
    return
  for i in cand:
    check(bs[:i] + bs[i+1:], [i + 1] + tmp)

check(bs, [])

if len(ans):
  for ai in ans[0]:
    print(ai)
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

N = int(raw_input())
bs = map(int, raw_input().split(" "))

def calc(bbs, ls):
    if len(bbs) == 1 and bbs[0] == 1:
        a = ls+[1]
        a.reverse()
        for aa in a:
            print aa
        return True
    for i in range(len(bbs)):
        if i + 1 == bbs[i]:
            if calc(bbs[:i]+bbs[i+1:], ls+  [i+1]):
                return True
    return False
if not calc(bs, []):
    print "-1"

Submission status: Time Limit Exceeded

Solution code:
import copy

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


def dfs(arr, indexes):
    if len(arr) == 0:
        return indexes

    for i in reversed(range(len(arr))):
        if i+1 == arr[i]:
            _indexes = copy.copy(indexes)
            _indexes.append(i)
            res = dfs(arr[:i] + arr[i+1:], _indexes)
            if res:
                return res
    return False


res = dfs(B, [])
if res:
    for i in reversed(res):
        print(i+1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import copy

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


def dfs(arr, indexes):
    if len(arr) == 0:
        return indexes

    for i in range(len(arr)):
        if i+1 == arr[i]:
            _indexes = copy.copy(indexes)
            _indexes.append(i)
            res = dfs(arr[:i] + arr[i+1:], _indexes)
            if res:
                return res
    return False


res = dfs(B, [])
if res:
    for i in reversed(res):
        print(i+1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import copy
import queue


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

    q = queue.Queue()
    q.put((B, []))

    def bfs(arr, indexes):
        if len(arr) == 0:
            return indexes

        for i in range(len(arr)):
            if i+1 == arr[i]:
                _indexes = copy.copy(indexes)
                _indexes.append(i)
                q.put((arr[:i] + arr[i+1:], _indexes))

        return False

    while not q.empty():
        item = q.get()
        res = bfs(item[0], item[1])
        if res:
            for i in reversed(res):
                print(i+1)
            return
    print(-1)
    return


main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
b = [int(x) for x in input().split()]
li=[]
def dfs(B,li):
    if(B == []):
        return True
    if(max(B)>len(B)):
        return False
    for index,i in enumerate(B):
        if(index == i-1):
            if(index == 0):
                if(dfs(B[1:],li)):
                    li.append(i)
                    return True
            else:
                if(dfs(B[:index]+B[index+1:],li)):
                    li.append(i)
                    return True
    return False

if(dfs(b,li)):
    for i in li:
        print(i)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from math import factorial
input = sys.stdin.readline

N = int(input())
L = [int(v) for v in input().split()]
m = {}

def dfs(counter, now_list, remain):
    k = "".join(map(str, now_list))
    if m.get(k) != None and m[k] == [-1]:
        return m[k]

    if len(remain) == 0:
        if now_list == L:
            return []
    else:
        remain_local = [v for v in remain if v <= counter]
        if len(remain_local) == 0:
            return [-1]

        for v in remain_local:
            p = now_list.copy()
            p.insert(v - 1, v)

            r = remain.copy()
            r.remove(v)

            k = "".join(map(str, p))
            if m.get(k) != None and m[k] == [-1]:
                continue

            h = dfs(counter + 1, p, r)
            m[k] = h
            if h != [-1]:
                return h + [v]
    
    return [-1]

ans = dfs(1, [], L.copy())
if ans == [-1]:
    print(-1)
else:
    ans = reversed(ans)
    [print(v) for v in ans]

Submission status: Time Limit Exceeded

Solution code:
import sys
from math import factorial
input = sys.stdin.readline

N = int(input())
L = [int(v) for v in input().split()]

def dfs(counter, now_list, remain):
    if len(remain) == 0:
        if now_list == L:
            return []
    else:
        remain_local = [v for v in remain if v <= counter]
        if len(remain_local) == 0:
            return [-1]

        for v in remain_local:
            p = now_list.copy()
            p.insert(v - 1, v)

            r = remain.copy()
            r.remove(v)

            h = dfs(counter + 1, p, r)
            if h != [-1]:
                return h + [v]
    
    return [-1]

ans = dfs(1, [], L.copy())
if ans == [-1]:
    print(-1)
else:
    ans = reversed(ans)
    [print(v) for v in ans]

Submission status: Time Limit Exceeded

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

# solve
ans = []

# check if _b can be constructed.
# returns True/False
def dfs(_b, _ans):
	
	for i in range(0, len(_b)):
		
		if i + 1 == _b[i]:
			_b2 = _b[:]
			_ans2 = _ans[:]
			_ans2.append(_b2[i])
			_b2.pop(i)
			
			if dfs(_b2, _ans2) == True:
				return True
	
	if len(_b) == 0:
		## print answer
		_ans.reverse()
		for i in _ans:
			print(i)
		return True
		
	else:
		return False


if not dfs(b,[]):
	print(-1)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
b = list(map(int, input().split()))
a = [1, 2, 3, 4, 5]

def f(a, ans):
    if len(a) == 0:
        for i in range(len(ans)):
            print(ans[len(ans) - i - 1])
        exit()
    for i in range(len(a)):
        if i + 1 == a[i]:
            f(a[0:i] + a[i + 1:len(a)], ans + [i + 1])

f(b, [])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    # b = list(map(int, input().split()))
    b = [int(i) for i in input().split()] 
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)
  
  if check(b,N) != True:
    print(-1)
    
def check(B,lenB):
  # if 'get_ipython' in globals(): print(B)
  if lenB == 0 :
    return True
  #for i in reversed(range(lenB)):
  for i in range(lenB-1,-1,-1):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):],lenB -1 ) == True:
        print(B[i])
        return True
        break
  return False  

main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    # b = list(map(int, input().split()))
    b = [int(i) for i in input().split()] 
  else:
    b = [1,2,1]
    # b = [2,2]
    # b = [1,1,1,2,2,1,2,3,2]
    N = len(b)
  
  if check(b,N) != True:
    print(-1)
    
def check(B,lenB):
  # if 'get_ipython' in globals(): print(B)
  if lenB == 0 :
    return True
  #for i in reversed(range(lenB)):
  for i in range(lenB-1,-1,-1):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):],lenB -1 ) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    # b = list(map(int, input().split()))
    b = [int(i) for i in input().split()] 
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)
    
  if check(b) != True:
    print(-1)
    
def check(B):
  # if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  #for i in reversed(range(lenB)):
  for i in range(lenB-1,-1,-1):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    # b = list(map(int, input().split()))
    b = [int(i) for i in input().split()] 
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)
    
  if check(b) != True:
    print(-1)
    
def check(B):
  # if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  else :
    maxB = max(B)
    if maxB > lenB: maxB = lenB
  # for i in reversed(range(lenB)):
  for i in reversed(range(0,maxB)):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
import sys

def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    # b = list(map(int, input().split()))
    b = [int(i) for i in input().split()] 
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)
    
  if check(b) != True:
    print(-1)
    
def check(B):
  # if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  for i in reversed(range(lenB)):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
import sys

def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    b = list(map(int, input().split()))
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)

  if max(b) > N:
    print(-1)
    sys.exit()
    
  if check(b) != True:
    print(-1)
    
def check(B):
  # if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  for i in reversed(range(lenB)):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    b = list(map(int, input().split()))
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)
   
  if check(b) != True:
    print(-1)
    
def check(B):
  # if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  for i in reversed(range(lenB)):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    b = list(map(int, input().split()))
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)

  if check(b) != True:
    print(-1)
    
def check(B):
  # if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  for i in range(lenB):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
        break
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  if 'get_ipython' not in globals():  
    # For Subsession
    N = int(input())
    b = list(map(int, input().split()))
  else:
    # b = [1,2,1]
    # b = [2,2]
    b = [1,1,1,2,2,1,2,3,2]
    N = len(b)

  if check(b) != True:
    print(-1)
    
def check(B):
  if 'get_ipython' in globals(): print(B)
  lenB = len(B)
  if lenB == 0 :
    return True
  for i in range(lenB):
    if B[i] == i+1:
      if check(B[:i]+B[(i+1):]) == True:
        print(B[i])
        return True
    
main()

Submission status: Time Limit Exceeded

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

def solve(b):
    if len(b) == 0:
        return []
    ls = [(i+1, b[i]) for i in range(len(b)) if i+1 == b[i]]
    ls.sort(reverse=True)
    for i, _ in ls:
        a = solve(b[:i-1] + b[i:])
        if a != None:
            return [i] + a
    return None

a = solve(b)
if a == None:
    print(-1)
else:
    a.reverse()
    print('\n'.join(map(str, a)))

Submission status: Time Limit Exceeded

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

def solve(b):
    if len(b) == 0:
        return []
    for i in range(len(b)):
        if b[i] == i+1:
            a = solve(b[:i] + b[i+1:])
            if a != None:
                return [i+1] + a
    return None

a = solve(b)
if a == None:
    print(-1)
else:
    a.reverse()
    print('\n'.join(map(str, a)))

Submission status: Time Limit Exceeded

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

def solve(b):
    if len(b) == 0:
        return []
    for i in range(len(b)):
        if b[i] == i+1:
            a = solve(b[:i] + b[i+1:])
            if a != None:
                return [i+1] + a
    return None

a = solve(b)
if a == None:
    print(-1)
else:
    a.reverse()
    print('\n'.join(map(str, a)))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
bs = list(map(int, input().split()))
ans = [0] * n

def chk(numbers, ans, n):
    m = len(numbers)
    if m == 1:
        if numbers == [1]:
            ans[n-1] = 1
            return True
        else:
            return False
    cnt = 0
    for i, b in enumerate(numbers):
        if b == i+1:
            cnt += 1
            ans[n-m] = b
            tempns = numbers.copy()
            tempns.pop(i)
            if chk(tempns, ans, n):
                return True
    if cnt == 0:
        ans[n-m] = 0
    return False

chk(bs, ans, n)

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

Submission status: Time Limit Exceeded

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

ans = []

def f(q, i, x):
  cnt = 0
  if i > N:
    if b == q:
      ans.append(x)
    return
  for j in s:
    if j > i:
      continue
    f(q[:j-1] + [j] + q[j-1:], i+1, x + [j])
  return

f([], 1, [])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import copy


def check_nn(b_):
    n_ = len(b_)
    # print(b_)

    if b_ == [1]:
        return [1]

    nn = np.zeros(n_)
    for ii in range(n_):
        if b_[ii] == ii+1:
            nn[ii] = 1

    tsum = int(sum(nn))

    if tsum == 0:
        return -1

    # if n_ == 1 and tsum == 1:
    #     ans_ = [1]

    tind = np.where(nn == 1)
    # print(tind)
    for ii in range(tsum):
        # tp = b_.pop[tind[ii]]
        tempb = copy.deepcopy(b_)
        # print(tind[0][ii])
        tp = tempb.pop(tind[0][ii])
        ans_ = check_nn(tempb)
        if ans_ != -1:
            # ans_.insert(0, tp)
            ans_.append(tp)
            return ans_

    return -1


n = input().rstrip().split(' ')
b = list(map(int, input().rstrip().split(' ')))
# ans = list()

# print(type(b))

ans = check_nn(b)

# print(ans)

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

Submission status: Time Limit Exceeded

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

stack=[]
for i in range(len(b)):
    if b[i]==i+1:
        stack.append([[i+1],b[:i]+b[i+1:]])

while len(stack)>0:
    s,c = stack.pop()
    if len(c)==0:
        for i in range(N):
            print(s[-i-1])
        exit()
    for i in range(len(c)):
        if c[i]==i+1:
            stack.append([s+[i+1],c[:i]+c[i+1:]])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.stdin.readline()

input_list = [int(x) for x in sys.stdin.readline().split(" ")]
#input_list = [1]
record = {}
def solve(input_list):
  # Return answer list if answer is found, False otherwise
  
  if (tuple(input_list) in record):
    return record[tuple(input_list)]
    
  if (len(input_list) == 0):
    return []
  else:
    
    for i in range(len(input_list)):
      if input_list[i] > len(input_list):
        return False

      if (input_list[i] == i + 1):
        copy = list(input_list)
        #print(i)
        copy.pop(i)
        result = solve(copy)
        if (not result == False):
          record[tuple(input_list)] = result + [i + 1]
          return result + [i + 1]

    return False

#print('aa')
answer = solve(input_list) 
 
if (answer):
  for number in answer:
    print (number)
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.stdin.readline()

input_list = [int(x) for x in sys.stdin.readline().split(" ")]
#input_list = [1]
def solve(tail, input_list):
  # Return answer list if answer is found, False otherwise
  if (len(input_list) == 0):
    return tail
  else:
    
    for i in range(len(input_list)):
      if (input_list[i] == i + 1):
        copy = list(input_list)
        tail_copy = list(tail)
        #print(i)
        copy.pop(i)
        tail_copy.insert(0, i + 1)
        result = solve(tail_copy, copy)
        if (result):
          return result
    return False

#print('aa')
answer = solve([], input_list) 
 
if (answer):
  for number in answer:
    print (number)
else:
  print(-1)

Submission status: Time Limit Exceeded

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

def bfs(queue):
    c,prev = queue.pop(0)
    ret = 0
    l = len(c)
    for i in range(l):
        if c[i] == i+1:
            app = []
            if i==0:
                app = c[1:]
            elif i==l:
                app = c[:-1]
            else:
                app = c[:i] + c[i+1:]
            pr = [i+1] + prev
            if app == []:
                ret = 1
            queue.append([app,pr])
    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: Time Limit Exceeded

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)):
            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: Time Limit Exceeded

Solution code:
N = int(input())
b = [int(x) for x in input().split()]
li=[]
def dfs(B,li):
    if(B == []):
        return True
    for index,i in enumerate(B):
        if(index == i-1):
            if(index == 0):
                if(dfs(B[1:],li)):
                    li.append(i)
                    return True
            else:
                if(dfs(B[:index]+B[index+1:],li)):
                    li.append(i)
                    return True
    return False

if(dfs(b,li)):
    for i in li:
        print(i)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int,input().split()))
def f(a):
  if len(a) == 0:
    return []
  for i in range(len(a)):
    if a[i] == i+1:
      b = a.copy()
      b.pop(i)
      ret = f(b)
      if ret == [-1]:
        continue
      ret.append(i+1)
      return ret
    else:
      continue
  else:
    return [-1]
ret = f(a)
print('\n'.join(map(str,ret)))

Submission status: Time Limit Exceeded

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:
                        for i in so:
                                print(i)
                        exit()
                return 0
        for i in range(1,x+2):
                ans.insert(i-1,i)
                so.append(i)
                dfs(x+1,ans,so)
                ans.pop(i-1)
                so.pop()
        return -1
print(dfs(0,[],[]))

Submission status: Time Limit Exceeded

Solution code:
import copy


def insertion(n, x):
    if not x:
        return True
    for i in range(n - 1, -1, -1):
        y = copy.copy(x)
        if y[i] == i + 1:
            y.pop(i)
            ope.insert(0, i + 1)
            if insertion(n - 1, y):
                return True
            else:
                ope.pop(0)
    return False


n = int(input())
b = list(map(int, input().split()))
ope = []
if insertion(n, b):
    for i in ope:
        print(i)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
"""
A - Limited Insertion
"""
import numpy as np

N = input()
b_list = list(map(int, input().split()))
# N = 9
# b_list = [1, 1, 1, 2, 2, 1, 2, 3, 2]
# b_list = [1,1,1,2,2,1,2,3,2]
# b_list = [1,1,3,1,2]
# b_list = [2,2]


def make_idx(tmp_list):
    idx_list = np.arange(1, len(tmp_list)+1, 1)[::-1]
    return idx_list

b_list = b_list[::-1]
idx_list = make_idx(b_list)
rm_list = []

while len(b_list):
    for idx, b in zip(idx_list, b_list):
        if idx==b:
            b_list = b_list[::-1]
            b_list.remove(b)
            rm_list.append(b)
            b_list = b_list[::-1]
            break
        elif idx-b<0:
            print(-1)
#             exit()
    idx_list = make_idx(b_list)
    
for r in rm_list[::-1]:
    print(r)

Submission status: Time Limit Exceeded

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

def dfs(N, B, A, seq, nums):
  if len(A) == N:
    ok = True
    for a, b in zip(A, B):
      if a != b:
        ok = False
        break
    return seq if ok else None
  else:
    for n in nums.keys():
      if nums[n] > 0:
        tmpA = A.copy()
        tmpSeq = seq.copy()
        tmpNums = nums.copy()
        tmpA.insert(n-1,n)
        tmpSeq.append(n)
        tmpNums[n] -= 1
        ans = dfs(N, B, tmpA, tmpSeq, tmpNums)
        if ans:
          return ans

N = int(input())
B = list(map(int, input().split()))
ok = True
nums = {b:0 for b in B}
for i, b in enumerate(B):
  if i+1<b:
    ok = False
    break
  nums[b] += 1
if ok:
  for n in dfs(N,B,[],[],nums):
    print(n)
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
def check(X):
	#print(X,len(X))
	if(len(X)==1):
		if(X==[1]):
			return [1]
		else:
			return [-1]
	for i in range(len(X)):
		if(X[i]==i+1):
			c=check(X[:i]+X[i+1:])
			if(c!=[-1]):
				return c+[i+1]
	return [-1]



N=int(input())
B=input().split(" ")
B=[int(b) for b in B]

out=check(B)
for i in out:
	print(i)

Submission status: Time Limit Exceeded

Solution code:
import copy
N = int(input())
b = list(map(int,input().split()))
#delete exception
for i in range(N):
    if sum(1 for x in b[:i] if x<=b[i])+1 < b[i]:
        print(-1)
        exit()
def dfs(index, listed, list_a):
    global N,b
    if index==N:
        a = []
        for i in list_a:
            a.insert(i-1,i)
        if a==b:
            for i in list_a:
                print(i)
            exit()
    set_list = set(listed)
    for i in set_list:
        if i <= index+1:
            mobu_listed = copy.copy(listed)
            mobu_listed.remove(i)
            mobu_a = copy.copy(list_a)
            mobu_a.append(i)
            dfs(index+1, mobu_listed, mobu_a)
dfs(0, b, [])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
l=list(map(int,input().split()))
s=[]
flag=1
while len(l)!=0 or flag!=0:
    flag=0
    for i in range(len(l),0,-1):
        if i==l[i-1]:
            p=l[i-1]
            s.append(p)
            l.pop(i-1)
            flag=1
            break
ans=reversed(s)
ans=list(ans)
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:

def check(X):
	#print(X,len(X))
	if(len(X)==1):
		if(X==[1]):
			return [1]
		else:
			return [-1]
	for i in range(len(X)):
		if(X[i]==i+1):
			c=check(X[:i]+X[i+1:])
			if(c!=[-1]):
				return c+[i+1]
	return [-1]



N=int(input())
B=input().split(" ")
B=[int(b) for b in B]

out=check(B)
for i in out:
	print(i)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
b=list(map(int,input().split()))
ans=[]
while len(b)>0:
  for i in range(len(b),0,-1):
    if b[i-1]==i:
      ans.append(b.pop(i-1))
ans.reverse()
for i in range(n):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
BBB=[int(x) for x in input().split()]
 
BB=[0 for i in range(N)]
def re(B,n):
  global BB
  if n==1:
    if B[0]!=1:
      return -1
    BB[0]=B[0]
    for i in BB:
      print(i)
    exit()
  for i in range(n):
    if B[i]>i+1:
      return 1
    if B[i]==i+1:
      BB[n-1]=B[i]
      C=B.copy()
      del C[i]
      re(C,n-1)
  return -1 
result=re(BBB,N)
print(-1)

Submission status: Time Limit Exceeded

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

def solve(li):
  global output
  global suc
  if len(li)==0:
    suc=True
    for i in output:
      print(i)
  for index, value in enumerate(li):
    if index+1 == value:
      output.insert(0,li[index])
      ll=li[:]
      del ll[index]
      solve(ll)
  del output[0]


for i,v in enumerate(b):
  if suc: break
  if i+1 == v:
    output=[]
    output.append(i+1)
    bb = b[:]
    del bb[i]
    solve(bb)

if not(suc):
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
b = list(map(str, input().split()))
''.join(b)
ans = []
def dfs(b):
    if len(b) == 1:
        if int(b[0]) == 1:
            return True
    else:
        f = 0
        for j in range(len(b)):
            if int(b[j]) == j + 1:
                f += 1
            else:
                break
        if f == len(b):
            for j in range(1, len(b)):
                ans.append(b[j])
            return True

        for i in range(len(b) - 1, -1, -1):
            if int(b[i]) == i + 1:
                if i == 0:
                    if dfs(b[1:]):
                        ans.append(i + 1)
                        return True
                else:
                    if dfs(b[:i] + b[i+1:]):
                        ans.append(i + 1)
                        return True
        return False
if dfs(b):
    ans.insert(0, 1)
    for i in range(len(ans)):
        print(ans[i])
else:
    print(-1)

Submission status: Time Limit Exceeded

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


def delitable(numbers):
    return [v for i, v in enumerate(numbers) if v == i + 1]


b_searched = set()
b_unsearched = []


b_searched.add(tuple(b))
delit = delitable(b)

if delit == []:
    print("-1")
for delit_num in delit:
    b_unsearched.append([b[:delit_num - 1] + b[delit_num:], [delit_num]])


while b_unsearched:
    b, log = b_unsearched.pop()

    if b and max(b) > N - len(log):
        continue

    b_tuple = tuple(b)
    b_searched.add(b_tuple)
    delit = delitable(b)


    if not delit:
        if not b:
            log.reverse()
            print("\n".join(map(str, log)))
            break
        else:
            continue
    for delit_num in delit:
        b_temp = b[:delit_num - 1] + b[delit_num:]
        if not tuple(b_temp) in b_searched:
            b_unsearched.append([b_temp, log + [delit_num]])
else:
    print("-1")