Harryxun/stf_run huggingface dataset:
from heapq import heapify, heappop, heappush
from operator import add

while True:
    n, m, s, g1, g2 = map(int, input().split())
    s -= 1
    g1 -= 1
    g2 -= 1
    if not n:
        break
    pipes = [set() for _ in range(n)]
    for _ in range(m):
        b1, b2, c = map(int, input().split())
        b1 -= 1
        b2 -= 1
        pipes[b1].add((c, b2))
        pipes[b2].add((c, b1))

    dists = [[None] * n for _ in range(2)]

    for i in (0, 1):
        g = (g1, g2)[i]
        dist = dists[i]
        dist[g] = 0
        queue = list(pipes[g])
        heapify(queue)
        while queue:
            total_cost, base = heappop(queue)
            if dist[base] is not None:
                continue
            dist[base] = total_cost
            for next_cost, next_base in pipes[base]:
                if dist[next_base] is None:
                    heappush(queue, (total_cost + next_cost, next_base))

    dists = list(map(add, *dists))

    current_best = dists[s]
    queue = list(pipes[s])
    heapify(queue)
    visited = {s}
    while queue:
        total_cost, base = heappop(queue)
        if base in visited:
            continue
        visited.add(base)
        current_best = min(current_best, total_cost + dists[base])
        for next_cost, next_base in pipes[base]:
            if next_base not in visited:
                next_whole_cost = total_cost + next_cost + dists[next_base]
                if current_best > next_whole_cost:
                    heappush(queue, (total_cost + next_cost, next_base))

    print(current_best)

### FIXED CODE ###

from heapq import heapify, heappop, heappush
from operator import add

SENTINEL = 100000
while True:
    n, m, s, g1, g2 = map(int, input().split())
    s -= 1
    g1 -= 1
    g2 -= 1
    if not n:
        break
    pipes = [set() for _ in range(n)]
    rpipes = [set() for _ in range(n)]
    for _ in range(m):
        b1, b2, c = map(int, input().split())
        b1 -= 1
        b2 -= 1
        pipes[b1].add((c, b2))
        rpipes[b2].add((c, b1))

    dists = [[SENTINEL] * n for _ in range(2)]

    for i in (0, 1):
        g = (g1, g2)[i]
        dist = dists[i]
        dist[g] = 0
        queue = list(rpipes[g])
        heapify(queue)
        while queue:
            total_cost, base = heappop(queue)
            if dist[base] < SENTINEL:
                continue
            dist[base] = total_cost
            for next_cost, next_base in rpipes[base]:
                if dist[next_base] == SENTINEL:
                    heappush(queue, (total_cost + next_cost, next_base))

    dists = list(map(add, *dists))

    current_best = dists[s]
    queue = list(pipes[s])
    heapify(queue)
    visited = {s}
    while queue:
        total_cost, base = heappop(queue)
        if base in visited:
            continue
        visited.add(base)
        current_best = min(current_best, total_cost + dists[base])
        for next_cost, next_base in pipes[base]:
            if next_base not in visited:
                heappush(queue, (total_cost + next_cost, next_base))

    print(current_best)
A = [int(input()) for i in range(4)]
print(min(A[0]+A[1])+min(A[2]+A[3]))

### FIXED CODE ###

A = [int(input()) for i in range(4)]
print(min(A[0],A[1])+min(A[2],A[3]))
# 初期入力
N = int(input())
word = [ input() for i in range(N) ]

# 単語をキーに数を数えて辞書
from collections import Counter
kazu_word = Counter(word)

#一番多い単語を抜き出す
kazu_word_a = max(kazu_word.values()) #　内包表記の中で毎回MAXを計算するより出したほうが１回で済む
kazu_word_max =[i for i,v in kazu_word.items() if v == kazu_word_a )]
# kazu_word_max_sorted = sorted(kazu_word_max)
"""
print(kazu_word)
print(kazu_word_max)
"""
#print(*kazu_word_max_sorted,sep="\n")
print("\n".join(kazu_word_max.sort())) #sortedをやめて sortにした

### FIXED CODE ###

# 初期入力
N = int(input())
word = [ input() for i in range(N) ]

# 単語をキーに数を数えて辞書
from collections import Counter
kazu_word = Counter(word)

#一番多い単語を抜き出す
kazu_word_a = max(kazu_word.values()) #　内包表記の中で毎回MAXを計算するより出したほうが１回で済む
kazu_word_max =[i for i,v in kazu_word.items() if v == kazu_word_a ]
kazu_word_max_sorted = sorted(kazu_word_max)
"""
print(kazu_word)
print(kazu_word_max)
"""
print(*kazu_word_max_sorted,sep="\n")
temperature = int(input())
if tamperature < == 30:
  print('No)
else:
  print('Yes)

### FIXED CODE ###

t = int(input())
if t >= 30:
  print('Yes')
else:
  print('No')
def aaa(seat_list):
	return seat_list[len(seat_list)-1] - seat_list[0]

value = int(input())

people = 0
while True:
	try:
		seat = input()
		if seat:
			string_seat = seat.split()
			seat_list = []
			seat_list = [int(x) for x in (string_seat)]
			people += aaa(seat_list)
		except EOFError:
		break
print(people)


### FIXED CODE ###

value = int(input())
people = 0
while True:
	try:
		seat = input()
		if seat:
			string_seat = seat.split()
			seat_list = []
			seat_list = [int(x) for x in (string_seat)]
			people += seat_list[len(seat_list)-1] - seat_list[0]+1
	except EOFError:
		break
# while True:
# 	seat = input()
# 	if seat:
# 		string_seat = seat.split()
# 		seat_list = []
# 		seat_list = [int(x) for x in (string_seat)]
# 		people += aaa(seat_list)
# 	else:
# 		break
print(people)
a, b = map(int,input().split())
if a == 1,3,5,7,8,10:
 if b == 3,5,7,8,10,12:
   print("Yes")
 else:
   print("No")
elif a == 4,6,9:
 if b == 6,9,11:
  print("Yes")
 else:
  print("No")
else:
 print("No")

### FIXED CODE ###

a,b = map(int,input().split())
listA =[1,3,5,7,8,10,12]
listB =[4,6,9,11]
if a in listA and b in listA:
 print("Yes")
elif a in listB and b in listB:
 print("Yes")
else:
 print("No")
N=input()
if N=='1':print("Hello World")
else:
    l=list(map(int,N.split()))
    print(l[1]+l[2])

### FIXED CODE ###

i=input;
print('Hello World') if '1'==i() else print(int(i())+int(i()))
k = int(input())
a,b = map(int,input())
d = 0
for i in range(a,b+1):
  if i%k == 0:
    d += 1
    break
  else:
    d = 0
if d == 1:
  print('OK')
else:
  print('NG')

### FIXED CODE ###

k = int(input())
a,b=map(int,input().split())
count = 0
for i in range(a,b+1):
    if i%k == 0:
        count += 1
if count == 0:
    print("NG")
else:
    print("OK")
S = input()
if S[0]==S[1]orS[1]==S[2]:
  print("Yes")
else:
  print("No")

### FIXED CODE ###

S = input()
if S[0]==S[1] and S[0]==S[2]:
  print("No")
else:
  print("Yes")
n,l=map(int, input().split())
ss=[input() for i in range(n)]
ss=ss.sort()
print(''.join(ss))


### FIXED CODE ###

n,l=map(int, input().split())
ss=[input() for i in range(n)]
ss.sort()
print(''.join(ss))
import functools

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


total_votes_checker = lambda M, total_votes: (False 
                                        if total_votes < 1 / (4 * M) 
                                        else True)

total_votes = sum(A)

#item_num_checker = lambda N, A: True if len(A) == N else False

popular_checker = lambda A, M: True if A[M] == max(A) else False

total_votes_checker(M, total_votes)
popular_checker(A,M)

TF = total_votes_checker(M, total_votes) and popular_checker(A,M)

printer = lambda TF = print("yes") if True else print("No")

printer(TF)

### FIXED CODE ###

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

total_votes = sum(A)

total_votes_checker = lambda M, i, total_votes: (False if i < (1 / (4 * M)) * total_votes else True)

A = list(filter(lambda i: total_votes_checker(M, i, total_votes), A))

print("Yes") if len(A) >= M else print("No")
N, X = map(int, input().split())
city_lst = list(map(int, input().split()))
city_lst.sort()
dif_lst = []
for i in range(1, N):
	dif_lst.append(city_lst[i] - city_lst[i - 1])
# print(city_lst)

if X < city_lst[0]:
	maximum_D = city_lst[0] - X
else:
	for i in range(N - 1):
		if city_lst[i] < X:
			maximum_D = min(abs(X - city_lst[i]), abs(city_lst[i + 1] - X))
			break

# print(maximum_D)
for D in reversed(range(1, maximum_D + 1)):
	fail = 0
	# print("D = {}".format(D))
	for dif in dif_lst:
		if dif % D != 0:
			# print(city_lst[i], city_lst[i - 1])
			fail = 1
			# print("fail = 1")
			break
	if not fail:
		print(D)
		break

### FIXED CODE ###

from fractions import gcd

N, X = (int(i) for i in input().split())

x = [abs(int(i) - X) for i in input().split()]  
for i in range(1,N):
	x[i] = gcd(x[i-1], x[i])

print(x[-1])
n= int(input())
s = input()
ans = 0
li_r = []
li_g = []
li_b = []
for i in range(n):
  if li[i] == "R":
    li_r.append(i+1)
  elif li[i] == "G":
    li_g.append(i+1)
  elif li[i] == "B":
    li_b.append(i+1)
for i in li_r:
  for j in li_g:
    if 2*j - i in li_b:
      ans += len(li_b) -1
    else:
      ans += len(li_b)
print(ans)

### FIXED CODE ###

#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**7)
import bisect
import heapq
import itertools
import math
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from math import gcd
from operator import add, itemgetter, mul, xor
def cmb(n,r,mod):
  bunshi=1
  bunbo=1
  for i in range(r):
    bunbo = bunbo*(i+1)%mod
    bunshi = bunshi*(n-i)%mod
  return (bunshi*pow(bunbo,mod-2,mod))%mod
mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

#bisect.bisect_left(list,key)はlistのなかでkey未満の数字がいくつあるかを返す
#つまりlist[i] < x となる i の個数
#bisect.bisect_right(list, key)はlistのなかでkey以下の数字がいくつあるかを返す
#つまりlist[i] <= x となる i の個数
#これを応用することで
#len(list) - bisect.bisect_left(list,key)はlistのなかでkey以上の数字がいくつあるかを返す
#len(list) - bisect.bisect_right(list,key)はlistのなかでkeyより大きい数字がいくつあるかを返す
#これらを使うときはあらかじめlistをソートしておくこと！
n = I()
s = input()
c = Counter(s)
ans = 0
for i in range(n):
    for k in range(i+1,n):
        if (i+k)%2 == 0:
            j = (i+k)//2
            if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
                ans+=1
ans_2 = c["R"]*c["G"]*c["B"]
print(ans_2-ans)
n=int(input())
string_list=[input() for i in range(n)]
b=[i.sort() for i in strint_list]
g=0
for i  in b:
    g+=(l.count(i)-1)
print(int(g*0.5))

### FIXED CODE ###

import math
import collections

n=int(input())
a=[list(input()) for i in range(n)]
b=[str(sorted(list(i))) for i in a]
count=list(collections.Counter(b).values())
count=[i for i in count if i>1]
print(int(sum([math.factorial(x)/(math.factorial(x-2)*2) for x in count])))
n,x = (int(i) for i in input().split())  
l = [int(i) for i in input().split()] 
d = 0
i=0
type(l)
while d <= x:
   d+=l[i]
   i+=1 

print(i) 

### FIXED CODE ###

n,x = (int(i) for i in input().split())  
l = [int(i) for i in input().split()] 
d = 0
i=0
while d <= x:
    try:
        d+=l[i]
    except:
        i+=1
        break
    i+=1

print(i)
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 21:09:45 2019

@author: iwata
"""

N, M = map(int, input().split())
anew = []         

a = list(map(int, input().split()))
for i in range(1,len(a)):
    anew.append(a[i])

for j in range(1,N):
    a = list(map(int, input().split()))
    for k in range(1, len(a)):
        anew.append(a[k])
    anew_duplicate = [x for x in set(anew) if anew.count(x) > 1]
    anew = anew_duplicate 
print(len(anew_duplicate))

### FIXED CODE ###

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 21:09:45 2019

@author: iwata
"""

N, M = map(int, input().split())
anew = []         

a = list(map(int, input().split()))
for i in range(1,len(a)):
    anew.append(a[i])

if N==1:
    print(len(anew))
else:
    for j in range(1,N):
        a = list(map(int, input().split()))
        for k in range(1, len(a)):
            anew.append(a[k])
        anew_duplicate = [x for x in set(anew) if anew.count(x) > 1]
        anew = anew_duplicate 
    print(len(anew_duplicate))
#https://atcoder.jp/contests/abc167/tasks/abc167_c C - Skill Up
import numpy as np
from itertools import combinations
N,M,X=list(map(int,input().split()))
book_dict={}
for i in range(M):
    book_dict[i] = list(map(int,input().split()))

answer = 10**5*12+1
for i in range(M,0,-1):
    for v in combinations(book_dict.keys(), i):
        search_book = list(map(lambda x:book_dict[x],list(v)))
        sum_search_book = np.array(np.sum(search_book,axis = 0))
        if (np.count_nonzero(sum_search_book[1:] >= X) == N) and sum_search_book[0] < answer:
            answer = sum_search_book[0]
                                                                                 
           
        
        
    
if answer == 10**5*12+1:
    answer = -1

print(answer)


### FIXED CODE ###

#https://atcoder.jp/contests/abc167/tasks/abc167_c C - Skill Up
import numpy as np
from itertools import combinations
N,M,X=list(map(int,input().split()))
book_dict={}
for i in range(N):
    book_dict[i] = list(map(int,input().split()))

answer = (10**5*12)+1
for i in range(N,0,-1):
    for v in combinations(book_dict.keys(), i):
        search_book = list(map(lambda x:book_dict[x],list(v)))
        sum_search_book = np.array(np.sum(search_book,axis = 0))
        if (np.count_nonzero(sum_search_book[1:] >= X) == M) and sum_search_book[0] < answer:
            answer = sum_search_book[0]
                                                                                 
    
if answer == (10**5*12)+1:
    answer = -1

print(answer)
n=int(input())
edges=[[] for i in range(n)]
import sys
input=sys.stdin.buffer.readline
sys.setrecursionlimit(10**9)
for i in range(n-1):
    a,s,w=map(int,input().split())
    edges[a-1].append([s-1,w]);edges[s-1].append([a-1,w])
colors=[-1]*n
colors[0]=1
def dfs(now):
    for to,cost in edges[now]:
        if colors[to]==-1:
            colors[to]=(cost+colors[now])%2
            dfs(to)

dfs(0)
print(*colors,sep="\n")


### FIXED CODE ###

n=int(input())
edges=[[] for i in range(n)]
import sys

sys.setrecursionlimit(10**9)
for i in range(n-1):
    a,s,w=map(int,input().split())
    edges[a-1].append([s-1,w]);edges[s-1].append([a-1,w])
colors=[-1]*n
colors[0]=1
def dfs(now):
    for to,cost in edges[now]:
        if colors[to]==-1:
            colors[to]=(cost+colors[now])%2
            dfs(to)

dfs(0)
print(*colors,sep="\n")
x=input()
print(x+(int)(pow(x,2)+(int)(pow(x,3)))

### FIXED CODE ###

x=(int)(input())
y=x+(int)(pow(x,2))+(int)(pow(x,3))
print("{}".format(y))
from collections import defaultdict as d
a=[int(input()) for i in range(int(input()))]
b=sorted(a)
c=d(int)
e=0
for i in range(0,n,2):
    d[b[i]]=1
for i in a[1::2]:
    e+=d[i]
print(e)

### FIXED CODE ###

from collections import defaultdict as d
a=[int(input()) for i in range(int(input()))]
b=sorted(a)
c=d(int)
e=0
for i in b[::2]:
    c[i]=1
for i in a[1::2]:
    e+=c[i]
print(e)
d=input()
if d=25:
  print('christmas')
    
elif d=24:
  print('Christmas Eve')

elif d=23:
  print('Christmas Eve Eve')
else :
  print('Christmas Eve Eve Eve')
 

### FIXED CODE ###

d=int(input())
if d==25:
  print('Christmas') 
elif d==24:
  print('Christmas Eve')
elif d==23:
  print('Christmas Eve Eve')
else :
  print('Christmas Eve Eve Eve')
K, X = map(int,input().split())
if 500 * K => X:
    print("Yes")
else:
    print("No")

### FIXED CODE ###

K, X = map(int,input().split())
if 500 * K >= X:
    print("Yes")
else:
    print("No")
import math
N,K=map(int,input().split())
def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
for i in range(K):
  ans=combinations_count(N-K+1,i+1)*combinations_count(K-1,i)
  ANS=ans%(10**9+7)
  print(ANS)

### FIXED CODE ###

import math
N,K=map(int,input().split())
def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
for i in range(K):
  if N-K>i:
    ans=combinations_count(N-K+1,i+1)*combinations_count(K-1,i)
    ANS=ans%(10**9+7)
    print(ANS)
  elif N-K==i:
    ans=combinations_count(K-1,i)
    ANS=ans%(10**9+7)
    print(ANS)
  else:
    print(0)
import fractions

N, M = map(int, input().split())
S = input()
T = input()
L = N*M//fractions.gcd(N, M)

def S_ni_naru(X_S, S, L, N):
    for i in range(N):
        idx = L//N*i
        X_S[idx] = S[i]
    return X_S


def T_ni_naru(X_T, T, L, M):
    for i in range(M):
        idx = L//M*i
        X_T[idx] = T[i]
    return X_T

X_S = S_ni_naru([0]*L, S, L, N)
X_T = T_ni_naru([0]*L, T, L, M)

for s, t in zip(X_S, X_T):
    if (s != t) and (s != 0) and (t != 0):
        print(-1)
        exit()

print(L)


### FIXED CODE ###

import sys
import fractions
N, M = map(int, input().split())
S = input()
T = input()

g = fractions.gcd(N, M)
L = N * M // g

ss = L // N
ts = L // M
for i in range(N):
  if (i * ss) % ts == 0:
    j = (i * ss) // ts
    if S[i] != T[j]:
      print(-1)
      sys.exit()

for i in range(M):
  if (i * ts) % ss == 0:
    j = (i * ts) // ss
    if T[i] != S[j]:
      print(-1)
      sys.exit()

print(L)
N, T = map(int, input().split())

AB = [tuple(map(int, input().split())) for _ in range(N)]


AB.sort()

dp = [[0 for _ in range(T)] for _ in range(N+1)]




for i in range(N):
    for j in range(T):
        if AB[i][0] > j:
            dp[i+1][j] = dp[i][j]
        else:
            dp[i+1][j] = max(dp[i][j], dp[i][j - AB[i][0]] + AB[i][1] )


# 使ってないものを探す

used = [False] * N
j = T-1
#print("j =", j)
for i in reversed(range(N)):
    if dp[i+1][j] == 0 or dp[i][j] == 0:
        break
    #for j in reversed(range(T)):
    # i を使う場合
    #print(i, dp[i][j - AB[i][0]] + AB[i][1] , dp[i][j])
    #print("i, j, dp(i+1,j), dp[i+1][j - AB[i][0]] + AB[i][1] ", i, j, dp[i+1][j], dp[i+1][j - AB[i][0]] + AB[i][1] )
    #print(i,j, AB[i][0])
    if dp[i][j - AB[i][0]] + AB[i][1] == dp[i+1][j]:
        used[i] = True
        j -= AB[i][0]
        #print("j =", j)
    
#print(used)

last = 0
for i in range(N):
    if not used[i]:
        last = max(last, AB[i][1])

print(dp[-1][-1] + last)

#print(dp)



### FIXED CODE ###


N, T = map(int, input().split())

AB = [tuple(map(int, input().split())) for _ in range(N)]


AB.sort()

dp = [[0 for _ in range(T)] for _ in range(N+1)]




for i in range(N):
    for j in range(T):
        if AB[i][0] > j:
            dp[i+1][j] = dp[i][j]
        else:
            dp[i+1][j] = max(dp[i][j], dp[i][j - AB[i][0]] + AB[i][1] )


ans = 0
for i, d in enumerate(dp):
    # dp[i][:]にはi-1番目までで最大の満足度が入れられてるから、ABのi以降（使ってないから）で一番大きいのを足す
    mb = 0
    for a,b in AB[i:]:
        mb = max(mb, b)
    ans = max(ans, d[-1] + mb)

print(ans)
S = list(input())
if S[0] == S[1] & S[1] == S[2]:
  print('No')
else:
  print("Yes")

### FIXED CODE ###

S = list(input())
if (S[0] == S[1]) & (S[1] == S[2]):
  print('No')
else:
  print("Yes")
# -*- coding: utf-8 -*-
#https://mathtrain.jp/tyohukuc

n, m, k = map(int,input().split())

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 998244353
N = n+1 # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

ans = 0
beki = [1,m-1]
for i in range(2,N+1):
    beki.append(((beki[-1]*(m-1)) % p))

for x in range(k+1):
    ans += m * beki[n-x-1] %p * cmb(n-1,x,p)) %p
    ans = ans % p
print(ans)


### FIXED CODE ###

# -*- coding: utf-8 -*-
#https://mathtrain.jp/tyohukuc

n, m, k = map(int,input().split())

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 998244353
N = n+1 # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

ans = 0
beki = [1,m-1]
for i in range(2,N+1):
    beki.append(((beki[-1]*(m-1)) % p))

for x in range(k+1):
    ans += m * beki[n-x-1] %p * cmb(n-1,x,p) %p
    ans = ans % p
print(ans)
n=int(input())
 
result=[]
for i in range(1,n+1):
    if i %3==0:
        result.append(i)
    else:
        k=i
        for j in range(1,len(str(n))+1):
            if k%10**==3:
                result.append(i)
                break
            else:
                k=k//10**j
        else:
            continue
 
print("",*result)

### FIXED CODE ###

n=int(input())
 
result=[]
for i in range(1,n+1):
    if i %3==0:
        result.append(i)
    else:
        k=i
        for j in range(1,5):
            if k%10==3:
                result.append(i)
                break
            else:
                k=k//10
        else:
            continue
 
print("",*result)
while True:
    h,w = map(int,input().split())
    if h==0 and w==0: break

    for i in range(h):
        for j in range(w):
            if (i+j)%2==0: print('#',end=='')
            else: print('.',end=='')
            if j==w-1: print()
    print()
    



### FIXED CODE ###

while True:
    h,w = map(int,input().split())
    if h==0 and w==0: break

    for i in range(h):
        s = ''
        for j in range(w):
            if (i+j)%2==0: s += '#'
            else: s+='.'
        print(s)
    print()
# coding: utf-8
import sys
from itertools import permutations,combinations

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 全探索
INF = 10 ** 5
answer = INF
N = ir()
A = lr()
B = lr()
for pattern in combinations(range(N), (N+1)//2):
    pattern = set(pattern)
    red = []
    blue = []
    for i in range(N):
        if i in pattern:
            red.append((B[i], i) if i&1 else (A[i], i))
        else:
            blue.append((A[i], i) if i&1 else (B[i], i))
    red.sort()
    blue.sort()
    temp = 0
    for i in range(N//2):
        if red[i][0] > blue[i][0]:
            break
        if i + 1 < len(red) and red[i+1] < blue[i]:
            break
        temp += abs(red[i][1] - 2 * i)
        temp += abs(blue[i][1] - (2 * i + 1))
    else:
        if N&1 and blue[-1][0] > red[-1][0]:
            continue
        temp //= 2
        if temp < answer:
            answer = temp

print(answer if answer != INF else -1)
# 12

### FIXED CODE ###

# coding: utf-8
import sys
from itertools import permutations,combinations
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 全探索
INF = 10 ** 5
answer = INF
N = ir()
if N == 1:
    print(0); exit()
A = lr()
B = lr()
for pattern in combinations(range(N), (N+1)//2):
    pattern = set(pattern)
    red = []
    blue = []
    for i in range(N):
        if i in pattern:
            red.append((B[i], i) if i&1 else (A[i], i))
        else:
            blue.append((A[i], i) if i&1 else (B[i], i))
    red.sort()
    blue.sort()
    result = []
    
    for i in range(N//2):
        if red[i][0] > blue[i][0]:
            break
        if i + 1 < len(red) and red[i+1][0] < blue[i][0]:
            break
        result.append(red[i][1])
        result.append(blue[i][1])
    else:
        if N&1 and blue[-1][0] > red[-1][0]:
            continue
        if N&1:
            result.append(red[-1][1])
        temp = 0
        used = set()
        for i in range(N):
            for x in used:
                if result[i] < x:
                    temp += 1
            used.add(result[i])            
        if temp < answer:
            answer = temp

print(answer if answer != INF else -1)
# 12
n=int(input())
ans=n*(n+1)*(n+2)//6
for i in range(n-1):
    u=map(int,input().split())
    ans-=min(u)*(n-max(u)+1)
print(ans)

### FIXED CODE ###

import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
# from scipy.sparse.csgraph import floyd_warshall
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations, combinations_with_replacement
from heapq import heappop, heappush, heapify
from fractions import gcd
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def main():
    n = int(input())
    ans = n*(n+1)*(n+2)//6
    for i in range(n-1):
        u,v = map(int,input().split())
        if u > v:
            u,v = v,u
        ans -= (u)*(n-v+1)
    print(ans)
    
if __name__ == "__main__":
    main()