Problem:


Score : 700 points

Problem Statement

We have N cards numbered 1, 2, ..., N.
Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side.
Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each i (1 \leq i \leq N - 1), the integer facing up on the (i+1)-th card from the left is not less than the integer facing up on the i-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

Choose an integer i (1 \leq i \leq N - 1).
Swap the i-th and (i+1)-th cards from the left, then flip these two cards.

Constraints

1 \leq N \leq 18

1 \leq A_i, B_i \leq 50 (1 \leq i \leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If it is impossible to have a non-decreasing sequence, print -1.
If it is possible, print the minimum number of operations required to achieve it.

Sample Input 1

3
3 4 3
3 2 3

Sample Output 1

1

By doing the operation once with i = 1, we have a sequence [2, 3, 3] facing up, which is non-decreasing.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

After any number of operations, we have the sequence [2, 1] facing up, which is not non-decreasing.

Sample Input 3

4
1 2 3 4
5 6 7 8

Sample Output 3

0

No operation may be required.

Sample Input 4

5
28 15 22 43 31
20 22 43 33 32

Sample Output 4

-1

Sample Input 5

5
4 46 6 38 43
33 15 18 27 37

Sample Output 5

3



Sample input:
3
3 4 3
3 2 3


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = -1

def chk(a):
    for i in range(N-1):
        if a[i] > a[i+1]:
            return False
    return True

def cnt(idx):
    res = 0
    for i in range(N):
        res += abs(idx[i] - i)
    return res // 2

for idx in permutations(range(N)):
    # print(idx)
    a = []
    for i in range(N):
        if (idx[i] % 2) ^ (i%2):
            a.append(B[idx[i]])
        else:
            a.append(A[idx[i]])
    # print(a)
    if chk(a):
        if ans == -1:
            ans = cnt(idx)
        else:
            ans = min(ans, cnt(idx))

print(ans)

Submission status: Time Limit Exceeded

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

c = []
for i in range(n):
    c.append((a[i], b[i]))


l = [i+1 for i in range(n)]
ans = 10**9

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


for v in itertools.permutations(l, n):
    tmp = 0
    cnt = 0
    for i in range(n):
        if tmp <= c[v[i]-1][(i-v[i]+1) % 2]:
            tmp = c[v[i]-1][(i-v[i]+1) % 2]
            cnt += 1
        else:
            break

    if cnt == n:
        bit = Bit(n)
        kaisu = 0
        for i in range(0, n):
            kaisu += i - bit.sum(v[i])
            bit.add(v[i], 1)
        ans = min(ans, kaisu)

print(ans if ans != 10**9 else -1)

Submission status: Time Limit Exceeded

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

res = []
# 0 = A , 1 = B
for bit in range(2 ** n):
    if str(bin(bit)).count('1') % 2 == 1:
        continue

    odds = []
    evens = []
    for i in range(n):
        if (bit >> i) & 1:
            card = B[i]
            check = (i + 1) % 2

        else:
            card = A[i]
            check = i % 2

        if check == 1:
            odds.append([card, i+1])
        else:
            evens.append([card, i+1])

    if 0 <= len(evens) - len(odds) <= 1:
        odds.sort(reverse=True)
        evens.sort(reverse=True)
        now = 0
        pattern = []
        for _ in range(len(evens)):
            num1, idx1 = evens.pop()

            if now <= num1:
                now = num1
                pattern.append(idx1)
                if odds:
                    num2, idx2 = odds.pop()
                    if now <= num2:
                        now = num2
                        pattern.append(idx2)
                    else:
                        break

            else:
                break
        else:
            res.append(pattern)


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

ans = []
for pattern in res:
    count = 0
    for i in range(n-1):
        num = pattern[i]
        check = pattern[i+1:]
        for t in check:
            if t < num:
                count += 1

    ans.append(count)

print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)
n = int(input())
a_lis = list(map(int, input().split()))
b_lis = list(map(int, input().split()))
used = []
res = []
def rec(a_lis, b_lis, l):
    found = True
    pre = -1
    for a in a_lis:
        if a < pre:
            found = False
            break
        pre = a
    if found:
        res.append(l)
        return
    used.append((a_lis, b_lis))
    for i in range(len(a_lis) - 1):
        na_lis = a_lis[:i] + [b_lis[i + 1]] + [b_lis[i]] + a_lis[i + 2:]
        nb_lis = b_lis[:i] + [a_lis[i + 1]] + [a_lis[i]] + b_lis[i + 2:]
        if (na_lis, nb_lis) not in used:
            rec(na_lis, nb_lis, l + 1)
rec(a_lis, b_lis, 0)
if res:
    print(min(res))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
def iter_bit(k, LIMIT):
    v = (1 << k) - 1

    while v < LIMIT:
        yield v
        x = v & -v
        y = v + x
        v = (v & ~y) // x >> 1 | y


def solve(n, cards):
    dp = [{} for _ in range(1 << n)]
    dp[-1][0] = 0
    LIMIT = 1 << n

    for d in range(n):
        for state in iter_bit(n - d, LIMIT):
            scores = dp[state]
            k = state
            curr = 0
            while k:
                b = k & -k
                i = b.bit_length() - 1
                num = cards[i][(d - i) % 2]
                next_dp = dp[state ^ b]
                for score, left_num in scores.items():
                    if left_num > num:
                        continue
                    ns = score + curr
                    if ns not in next_dp or next_dp[ns] > num:
                        next_dp[ns] = num
                k ^= b
                curr += 1

    if len(dp[0]) > 0:
        return min(dp[0].keys())
    else:
        return -1


n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
cards = list(zip(aaa, bbb))
print(solve(n, cards))

Submission status: Time Limit Exceeded

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

od=[A[i] if i%2==0 else B[i] for i in range(N)]
ev=[B[i] if i%2==0 else A[i] for i in range(N)]

ans=float("inf")
for v in itertools.permutations(range(1,N+1),N):
  v=[i for i in v]
  n=0
  j=1
  for i in range(N):
    if i%2==0:
      if n>od[v[i]-1]:
        j=0
        break
      else:
        n=od[v[i]-1]
    else:
      if n>ev[v[i]-1]:
        j=0
        break
      else:
        n=ev[v[i]-1]
  if j==1:
    a=0
    r=list(range(1,N+1))
    while v:
      a+=r.index(v[0])
      r.remove(v[0])
      v.pop(0)
    ans=min(ans,a)
    
if ans==float("inf"):
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500000)
n = int(input())
a_lis = list(map(int, input().split()))
b_lis = list(map(int, input().split()))
used = []
res = []
def rec(a_lis, b_lis, l):
    found = True
    pre = -1
    for a in a_lis:
        if a < pre:
            found = False
            break
        pre = a
    if found:
        res.append(l)
        return
    used.append((a_lis, b_lis))
    for i in range(len(a_lis) - 1):
        na_lis = a_lis[:i] + [b_lis[i + 1]] + [b_lis[i]] + a_lis[i + 2:]
        nb_lis = b_lis[:i] + [a_lis[i + 1]] + [a_lis[i]] + b_lis[i + 2:]
        if (na_lis, nb_lis) not in used:
            rec(na_lis, nb_lis, l + 1)
rec(a_lis, b_lis, 0)
if res:
    print(min(res))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

class BinaryIndexedTree():
    def __init__(self, seq):
        self.size = len(seq)
        self.depth = self.size.bit_length()
        self.build(seq)
        
    def build(self,seq):
        data = seq
        size = self.size
        for i,x in enumerate(data):
            j = i+(i&(-i))
            if j < size:
                data[j] += data[i]
        self.data = data
        
    def __repr__(self):
        return self.data.__repr__()
        
    def get_sum(self,i):
        data = self.data
        s = 0
        while i:
            s += data[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        data = self.data
        size = self.size
        while i < size:
            data[i] += x
            i += i & -i
    
    def find_kth_element(self,k):
        data = self.data; size = self.size
        x,sx = 0,0
        dx = 1 << (self.depth)
        for i in range(self.depth - 1, -1, -1):
            dx = (1 << i)
            if x + dx >= size:
                continue
            y = x + dx
            sy = sx + data[y]
            if sy < k:
                x,sx = y,sy
        return x + 1

def Inversion(seq):
    seq = [i + 1 for i in seq]
    # seqは、1,2,...,Nの順列
    N = len(seq)
    bit = BinaryIndexedTree([0] * (N+1))
    inv = N*(N-1)//2
    for x in seq:
        inv -= bit.get_sum(x)
        bit.add(x,1)
    return inv

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

# 全探索。出来上がった列が単調増加かを判定。最小の移動回数が答え。存在しない場合は-1
# 最小の操作回数⇒転倒数
ptn = list(permutations(range(N)))

ans = - 1
for p in ptn:
#  print("p", p)
  line = []
  for itr, val in enumerate(p):
    if abs(itr - val) % 2 == 0:
      line.append(A[val])
    else:
      line.append(B[val])
#  print("line", line)
  if all([j >= i for i, j in zip(line,line[1:])]):
    print(Inversion(p))
    exit()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()

def main():
    N=int(input())
    A=[(x,i) for i,x in enumerate(map(int,input().split()))]
    B=[(x,i) for i,x in enumerate(map(int,input().split()))]
    l_odd,l_even=[],[]
    for i in range(N):
        if i%2:
            l_even.append(A[i])
            l_odd.append(B[i])
        else:
            l_even.append(B[i])
            l_odd.append(A[i])
    stack=[]
    stack.append((0,0,[],[True]*N))
    kouho=[]
    while stack:
        n,index,l,f=stack.pop()
        if index==N:
            kouho.append(l)
            continue
        
        if index%2:
            C=l_even
        else:
            C=l_odd
        for a in C:
            if a[0]>=n and f[a[1]]:
                f2=[False]*N
                for i in range(N):
                    f2[i]=f[i]
                f2[a[1]]=False
                l2=l+[a[1]]
                stack.append((a[0],index+1,l2,f2))
    ans=INF
    if kouho:
        for l in kouho:
            c=0
            n=0
            while True:
                f=True
                for i in range(N-1):
                    if l[i]>l[i+1]:
                        l[i],l[i+1]=l[i+1],l[i]
                        c+=1
                        f=False
                if f:
                    ans=min(ans,c)
                    break
        print(ans)
    else:
        print(-1)
    
            
    
    

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

if all(a[0] == a[i] for i in range(n)):
    print(0)
    exit()

pre = [1<<i for i in range(n)]
bitcnt = [0]*(1<<n)
bitcnt[1] = 1
for i in range(1<<(n-1)):
    bitcnt[2*i] = bitcnt[i]
    bitcnt[2*i+1] = bitcnt[i]+1

DP = [defaultdict(lambda : float("inf")) for i in range(n)]

for i in range(n):
    DP[i][1<<i] = 0

for i in range(n-1):
    nxt = [defaultdict(lambda : float("inf")) for i in range(n)]
    for j in range(n):
        last = a[j] if (i-j)%2 == 0 else b[j]
        for state, cost in DP[j].items():
            for to in range(n):
                if state>>to&1:
                    continue
                nlast = a[to] if (i+1-to)%2 == 0 else b[to]
                if last > nlast:
                    continue
                nstate = state + pre[to]
                ncost = cost
                ncost += bitcnt[state>>to]
                nxt[to][nstate] = min(nxt[to][nstate], ncost)
    DP = nxt
mask = (1<<n)-1
ans = float("inf")
for i in range(n):
    ans = min(ans, DP[i][mask])
if ans == float("inf"):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

class BinaryIndexedTree():
    def __init__(self, seq):
        self.size = len(seq)
        self.depth = self.size.bit_length()
        self.build(seq)
        
    def build(self,seq):
        data = seq
        size = self.size
        for i,x in enumerate(data):
            j = i+(i&(-i))
            if j < size:
                data[j] += data[i]
        self.data = data
        
    def __repr__(self):
        return self.data.__repr__()
        
    def get_sum(self,i):
        data = self.data
        s = 0
        while i:
            s += data[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        data = self.data
        size = self.size
        while i < size:
            data[i] += x
            i += i & -i
    
    def find_kth_element(self,k):
        data = self.data; size = self.size
        x,sx = 0,0
        dx = 1 << (self.depth)
        for i in range(self.depth - 1, -1, -1):
            dx = (1 << i)
            if x + dx >= size:
                continue
            y = x + dx
            sy = sx + data[y]
            if sy < k:
                x,sx = y,sy
        return x + 1

def Inversion(seq):
    seq = [i + 1 for i in seq]
    # seqは、1,2,...,Nの順列
    N = len(seq)
    bit = BinaryIndexedTree([0] * (N+1))
    inv = N*(N-1)//2
    for x in seq:
        inv -= bit.get_sum(x)
        bit.add(x,1)
    return inv

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

# 全探索。出来上がった列が単調増加かを判定。最小の移動回数が答え。存在しない場合は-1
# 最小の操作回数⇒転倒数
ptn = list(permutations(range(N)))

ans = - 1
for p in ptn:
#  print("p", p)
  line = []
  for itr, val in enumerate(p):
    if abs(itr - val) % 2 == 0:
      line.append(A[val])
    else:
      line.append(B[val])
#  print("line", line)
  if all([j >= i for i, j in zip(line,line[1:])]):
    # f(): pの転倒数を求める関数
    num = Inversion(p)
    if ans == -1:
      ans = num
    else:
      ans = min(ans, num)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from fractions import gcd
# from datetime import date, timedelta
# from heapq import *
import heapq
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
import sys
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline


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


def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors


def factorize(n):
    fct = []  # prime factor
    b, e = 2, 0  # base, exponent
    while b * b <= n:
        while n % b == 0:
            n = n // b
            e = e + 1
        if e > 0:
            fct.append((b, e))
        b, e = b + 1, 0
    if n > 1:
        fct.append((n, 1))
    return fct


def is_prime(n):
    if n == 1:
        return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True


def primes(n):
    is_prime = [True] * (n + 1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5) + 1):
        if not is_prime[i]:
            continue
        for j in range(i * 2, n + 1, i):
            is_prime[j] = False
    return [i for i in range(n + 1) if is_prime[i]]

def modpow(a, n, mod):
    res = 1
    while n > 0:
        if n & 1:
            res = res * a % mod
        a = a * a % mod
        n >>= 1
    return res


def modinv(a, mod):
    return modpow(a, mod - 2, mod)


def cnk(a, b):
    MOD = 10**9+7
    ret = 1
    for i in range(b):
        ret *= (a-i)
        ret %= MOD
        ret = ret * modinv(i+1, MOD) % MOD
    return ret




def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    
    l = []
    d = defaultdict(int)
    for i in range(n):
        if i % 2 == 0:
            l.append([a[i], i])
            d[(a[i],i)] = i + 1 
        else:
            l.append([b[i], i])
            d[(b[i], i)] = i + 1


    tree = [0] * (n+1)
    def BIT_update(tree, x):
        while x <= n:
            tree[x] += 1
            x += x & (-x)


    def BIT_sum(tree, x):
        s = 0
        while x:
            s += tree[x]
            x -= x & (-x)
        return s

            
    
    ans = float("inf")
    
    for ll in itertools.permutations(l):
        L = []
        for i in range(n):
            v,index = ll[i]
            if i % 2 == 0:
                L.append(v)
            else:
                if index % 2 == 0:
                    L.append(b[index])
                else:
                    L.append(a[index])
        f = True
        s = L[0]
        for i in range(1,n):
            if s <= L[i]:
                s = L[i]
            else:
                f = False
        if f:
            tree = [0] * (n+1)
            k = n*(n-1)//2
            for i in range(n):
                # lll.append(d[ll[i]])
                k -= BIT_sum(tree, d[tuple(ll[i])])
                BIT_update(tree,d[tuple(ll[i])])
            #print(L)
            ans = min(ans , k)

    
    if ans == float("inf"):
        print(-1)
    else:
        print(ans)
    

    


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy


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

    cards = []
    for i in range(N):
        cards.append([A[i], B[i]])

    if is_ok(cards):
        print(0)
        return

    checked = set()
    queue = [(cards, 0, -1)]
    while True:
        if len(queue) == 0:
            print(-1)
            return
        case = queue.pop(0)
        for i in range(N - 1):
            if i == case[2]:
                continue
            new_cards = change(case[0], i)
            str_cards = to_string(new_cards)
            if str_cards in checked:
                continue
            checked.add(str_cards)
            if is_ok(new_cards):
                print(case[1] + 1)
                return
            queue.append((new_cards, case[1] + 1, i))


def is_ok(cards):
    for i in range(len(cards) - 1):
        if cards[i][0] > cards[i + 1][0]:
            return False
    return True


def change(cards, i):
    cards = copy.deepcopy(cards)
    ia = cards[i + 1][1]
    ib = cards[i + 1][0]
    i2a = cards[i][1]
    i2b = cards[i][0]
    cards[i][0] = ia
    cards[i][1] = ib
    cards[i + 1][0] = i2a
    cards[i + 1][1] = i2b
    return cards


def to_string(cards):
    a = " ".join([str(c[0]) for c in cards]) + "\n"
    b = " ".join([str(c[1]) for c in cards]) + "\n"
    return a + b


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import collections

n = int(input())
cards = [[0, 0] for _ in range(n)]
for j in range(2):
    tmp = input().split(' ')
    for i in range(n):
        cards[i][j] = int(tmp[i])
visited = set()
q = collections.deque([([i for i in range(n)], 0)])
flag = 0

def get(i, x):
    if x % 2 == 0:
        return cards[x][i%2]
    return cards[x][1-i%2]

while q:
    status, step = q.popleft()
    if all(get(i, x) <= get(i+1, status[i+1]) for i, x in enumerate(status[:-1])):
        print(step)
        flag = 1
        break
    for i in range(n-1):
        tmp = status[:i] + [status[i+1], status[i]] + status[i+2:]
        key = tuple(tmp)
        if key not in visited:
          visited.add(key)
          q.append((tmp, step+1))
if flag == 0:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

pre = [1<<i for i in range(n)]
bitcnt = [0]*(1<<n)
bitcnt[1] = 1
for i in range(1<<(n-1)):
    bitcnt[2*i] = bitcnt[i]
    bitcnt[2*i+1] = bitcnt[i]+1

DP = [defaultdict(lambda : float("inf")) for i in range(n)]

for i in range(n):
    DP[i][1<<i] = 0

for i in range(n-1):
    nxt = [defaultdict(lambda : float("inf")) for i in range(n)]
    for j in range(n):
        last = a[j] if (i-j)%2 == 0 else b[j]
        for state, cost in DP[j].items():
            for to in range(n):
                if state>>to&1:
                    continue
                nlast = a[to] if (i+1-to)%2 == 0 else b[to]
                if last > nlast:
                    continue
                nstate = state + pre[to]
                ncost = cost
                ncost += bitcnt[state>>to]
                nxt[to][nstate] = min(nxt[to][nstate], ncost)
    DP = nxt
mask = (1<<n)-1
ans = float("inf")
for i in range(n):
    ans = min(ans, DP[i][mask])
if ans == float("inf"):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict


def solve(n, cards):
    dp = {(1 << n) - 1: {0: 0}}
    for d in range(n):
        ndp = defaultdict(lambda: defaultdict(lambda: 1000000))
        for state, scores in dp.items():
            k = state
            curr = 0
            while k:
                b = k & -k
                i = b.bit_length() - 1
                num = cards[i][(d - i) % 2]
                curr_dp = ndp[state ^ b]
                prev_num = 1000000
                for score, left_num in sorted(scores.items()):
                    if left_num > num:
                        continue
                    if prev_num <= left_num:
                        continue
                    curr_dp[score + curr] = min(curr_dp[score + curr], num)
                    prev_num = left_num
                k ^= b
                curr += 1

        if len(ndp) == 0:
            return -1
        dp = ndp
    if 0 in dp and len(dp[0]) > 0:
        return min(dp[0].keys())
    else:
        return -1


n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
cards = list(zip(aaa, bbb))
print(solve(n, cards))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

dp = [[-1] * (1<<n) for i in range(n)]
pre = [1<<i for i in range(n)]
DP = [defaultdict(lambda : float("inf")) for i in range(n)]

for i in range(n):
    DP[i][1<<i] = 0

for i in range(n-1):
    nxt = [defaultdict(lambda : float("inf")) for i in range(n)]
    for j in range(n):
        last = a[j] if (i-j)%2 == 0 else b[j]
        for state, cost in DP[j].items():
            for to in range(n):
                if state>>to&1:
                    continue
                nlast = a[to] if (i+1-to)%2 == 0 else b[to]
                if last > nlast:
                    continue
                nstate = state + pre[to]
                ncost = cost
                for k in range(to+1, n):
                    if state&pre[k]:
                        ncost += 1
                nxt[to][nstate] = min(nxt[to][nstate], ncost)
    DP = nxt
mask = (1<<n)-1
ans = float("inf")
for i in range(n):
    ans = min(ans, DP[i][mask])
if ans == float("inf"):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

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

def main():
    pti = time.time()
    n = int(input())
    a = tuple(map(int,input().split()))
    b = tuple(map(int,input().split()))

    dg = 10**7

    pp = 20

    dp = [10**5]*dg

    new = set([])
    for i in range(n):
        s = (1<<i)
        dp[s*pp+i] = i
        new.add(s*dg+i)
    

    for k in range(n-1):
        tank = set([])
        if len(new) == 0:
            break
        for popelt in new:
            s,idx = popelt//dg,popelt%dg
            if (k-idx)%2 == 0:
                fr = a[idx]
            else:
                fr = b[idx]
            cnt = 0
            for j in range(n):
                if (s>>j)&1 == 0:
                    if (j-k)%2 == 1:
                        val = a[j]
                    else:
                        val = b[j]
                    if val >= fr and dp[(s+(1<<j))*pp+j] > dp[s*pp+idx]+j-cnt:
                        dp[(s+(1<<j))*pp+j] = dp[s*pp+idx]+j-cnt
                        tank.add((s+(1<<j))*dg + j)
                else:
                    cnt += 1
        new = tank
    
    res = 10**5
    s = (2**n-1)*pp
    for i in range(n):
        if res > dp[s+i]:
            res = dp[s+i]
    if res == 10**5:
        print(-1)
    else:
        print(res)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
IAB = [(i, A[i], B[i]) for i in range(N)]

ans = 10**9
pos_0 = 0b101010101010101010
for color in range(2**N):
    C = [b if (color>>i)&1 else a for i,a,b in IAB]
    pos_1 = color ^ pos_0
    P = [(pos_1>>i)&1 for i in range(N)]

    C_sorted = sorted(C)

    n_operation = 0
    for i in range(N):
        found = False
        for j in range(i, N):
            if C[j]==C_sorted[i] and P[j]==i&1:
                found = True
                break

        if found:
            n_operation += j-i
            for j in range(j, i, -1):
                C[j], C[j-1] = C[j-1], C[j]
                P[j], P[j-1] = P[j-1], P[j]
        else:
            break
                
    if found:
        ans = min(ans, n_operation)
    
print(ans if ans < 10**9 else -1)

Submission status: Time Limit Exceeded

Solution code:
import math
import itertools
import copy

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

que = [[0,A,B]]
did_ques = [[A,B]]
while len(que) > 0:
    doingM = que[0][0]
    doingA = que[0][1]
    doingB = que[0][2]
    #逆転があるか確認
    for i in range(N-1):
        if doingA[i]>doingA[i+1]:
            break
    else:
        #逆転が無かった時
        print(doingM)
        break
    #逆転があった時
    #二個入れ替えてAc,Bcを作り、被りがなければ登録
    for i in range(N-1):
        Ac,Bc = copy.copy(doingA),copy.copy(doingB)
        Ac[i],Ac[i+1],Bc[i],Bc[i+1] = Bc[i+1],Bc[i],Ac[i+1],Ac[i]
        #did_quesにかぶってるか確認
        for did_que in did_ques:
            if Ac == did_que[0] and Bc == did_que[1]:
                break
        else:
            #かぶりが無かった時
            que.append([doingM+1, Ac, Bc])
            did_ques.append([Ac, Bc])
    #キューの先頭を削除
    que.pop(0)
if len(que) == 0:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

num_card = int(input())
alist = [int(v) for v in input().split()]
blist = [int(v) for v in input().split()]

base_faces = tuple(zip(alist, blist))

tried = set()

def is_increase(faces):
    temp = 0
    for f in faces:
        if temp <= f:
            temp = f
        else:
            return False
    return True

def swap_state(state, swap):
    a, b = swap, swap + 1
    state = list(state)
    state[a], state[b] = state[b], state[a]
    state[a] = (state[a][0], 1 - state[a][1])
    state[b] = (state[b][0], 1 - state[b][1])
    return tuple(state)

state_stack = deque([(0, tuple((i, 0) for i in range(num_card)))])
result = -1
while len(state_stack) > 0:
    count, state = state_stack.popleft()
    if state in tried:
        continue
    tried.add(state)
    
    faces = [base_faces[c][s] for c, s in state]
    if is_increase(faces):
        result = count
        break

    state_stack.extend(
        (count + 1, swap_state(state, swap))
        for swap in range(num_card - 1))

print(result)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict


def solve(n, cards):
    dp = {(1 << n) - 1: {0: 0}}
    for d in range(n):
        ndp = defaultdict(lambda: defaultdict(lambda: 1000000))
        for state, scores in dp.items():
            k = state
            curr = 0
            while k:
                b = k & -k
                i = b.bit_length() - 1
                num = cards[i][(d - i) % 2]
                for score, left_num in scores.items():
                    if left_num > num:
                        continue
                    ndp[state ^ b][score + curr] = min(ndp[state ^ b][score + curr], num)
                k ^= b
                curr += 1
        if len(ndp) == 0:
            return -1
        dp = ndp
    return min(dp[0].keys())


n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
cards = list(zip(aaa, bbb))
print(solve(n, cards))

Submission status: Time Limit Exceeded

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

def main():
    n = int(input())
    a = tuple(map(int,input().split()))
    b = tuple(map(int,input().split()))

    dg = 10**7

    dp = [[10**5]*n for i in range(2**n)]

    new = set([])
    for i in range(n):
        s = (1<<i)
        dp[s][i] = i
        new.add(s*dg+i)
    

    for k in range(n-1):
        tank = set([])
        if len(new) == 0:
            break
        for popelt in new:
            s,idx = popelt//dg,popelt%dg
            if (k-idx)%2 == 0:
                fr = a[idx]
            else:
                fr = b[idx]
            cnt = 0
            for j in range(n):
                if (s>>j)&1 == 0:
                    if (j-k)%2 == 1:
                        val = a[j]
                    else:
                        val = b[j]
                    if val >= fr and dp[s+(1<<j)][j] > dp[s][idx]+j-cnt:
                        dp[s+(1<<j)][j] = dp[s][idx]+j-cnt
                        tank.add((s+(1<<j))*dg + j)
                else:
                    cnt += 1  
        new = tank
    
    res = min(dp[2**n-1])

    if res == 10**5:
        print(-1)
    else:
        print(res)


if __name__ == '__main__':
    main()