Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

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

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
ans = 0

while len(A) != 0:
    i = A.pop(0)
    n = []
    for j in range(0, len(ring) - 1):
        check = min(ring[j:j + 2])
        n.append(check)
        if check == max(ring):
            break
    ans = ans + max(n)
    ring.insert(n.index(max(n)) + 1, i)

print(ans)

### FIXED CODE ###

import sys
from collections import deque

N = int(sys.stdin.readline())
A = [int(i) for i in sys.stdin.readline().split(' ')]

A.sort(reverse=True)
max_value = A.pop(0)
diff = deque([max_value])
ans = 0
for i in A:
    ans = ans + diff.popleft()
    diff.append(i)
    diff.append(i)

print(ans)
### BUGGY CODE ###

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

setA = set(A)

ans = 0
c = 0
for x in setA:
    for a in A:
        if a == x-1 or a == x or a == x+1:
            c += 1
    ans = max(ans, c)
    c = 0
print(ans)

### FIXED CODE ###

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

DA = {}
for a in A:
    if a in DA.keys():
        DA[a] += 1
    else:
        DA[a] = 1

ans = 0
c = 0
for k, v in DA.items():
    c += v
    if k+1 in DA:
        c += DA[k+1]
    if k-1 in DA:
        c += DA[k-1]
    ans = max(ans, c)
    c = 0
print(ans)
### BUGGY CODE ###

n,m,s,t=map(int,input().split())
TRAIN=[None]*m

for i in range(m):
    TRAIN[i]=list(map(int,input().split()))


YEN=[10**16]*(n+1)#sから国iまで行くときの最小円
SNOOK=[10**16]*(n+1)#国iからtまで行くときの最小スヌーク
YEN[s]=0
SNOOK[t]=0


TRAINMAP=[[] for i in range(n+1)]

for i in range(m):
    TRAINMAP[TRAIN[i][0]]+=[(TRAIN[i][1],TRAIN[i][2],TRAIN[i][3])]
    TRAINMAP[TRAIN[i][1]]+=[(TRAIN[i][0],TRAIN[i][2],TRAIN[i][3])]


checktown=s
checked=set()
alltown=set(list(range(1,n+1)))

while checked != alltown:
    for i in TRAINMAP[checktown]:
        if YEN[i[0]]>YEN[checktown]+i[1]:
            YEN[i[0]]=YEN[checktown]+i[1]


    checked=checked|{checktown}
    YENcheck=10**16

    for i in (alltown - checked):
        if YENcheck>YEN[i]:
            YENcheck=YEN[i]
            checktown=i




checktown=t
checked=set()
alltown=set(list(range(1,n+1)))

while checked != alltown:
    for i in TRAINMAP[checktown]:
        if SNOOK[i[0]]>SNOOK[checktown]+i[2]:
            SNOOK[i[0]]=SNOOK[checktown]+i[2]


    checked=checked|{checktown}
    SNOOKcheck=10**16

    for i in (alltown - checked):
        if SNOOKcheck>SNOOK[i]:
            SNOOKcheck=SNOOK[i]
            checktown=i



MONEY=[None]*(n+1)

for i in range(1,n+1):
    MONEY[i]=YEN[i]+SNOOK[i]


for i in range(1,n+1):
    print(10**15-min(MONEY[i:]))


### FIXED CODE ###

import heapq

n,m,s,t=map(int,input().split())
TRAIN=[None]*m

for i in range(m):
    TRAIN[i]=list(map(int,input().split()))


YEN=[10**16]*(n+1)#sから国iまで行くときの最小円
SNOOK=[10**16]*(n+1)#国iからtまで行くときの最小スヌーク
YEN[s]=0
SNOOK[t]=0


TRAINMAP=[[] for i in range(n+1)]

for i in range(m):
    TRAINMAP[TRAIN[i][0]]+=[(TRAIN[i][1],TRAIN[i][2],TRAIN[i][3])]
    TRAINMAP[TRAIN[i][1]]+=[(TRAIN[i][0],TRAIN[i][2],TRAIN[i][3])]



checking=[(0,s)]

while checking:

    cost,checktown=heapq.heappop(checking)
    
    for i in TRAINMAP[checktown]:
        if YEN[i[0]]>cost+i[1]:
            YEN[i[0]]=cost+i[1]
            heapq.heappush(checking,(cost+i[1],i[0]))

checking=[(0,t)]

while checking:

    cost,checktown=heapq.heappop(checking)
   
    for i in TRAINMAP[checktown]:
        if SNOOK[i[0]]>cost+i[2]:
            SNOOK[i[0]]=cost+i[2]
            heapq.heappush(checking,(cost+i[2],i[0]))



MONEY=[10**16]*(n+1)
MONEY[n]=YEN[n]+SNOOK[n]

for i in range(n-1,0,-1):
    if YEN[i]+SNOOK[i]<MONEY[i+1]:
        MONEY[i]=YEN[i]+SNOOK[i]
    else:
        MONEY[i]=MONEY[i+1]


for i in range(1,n+1):
    print(10**15-MONEY[i])
### BUGGY CODE ###

f=lambda:map(int,input().split())
n,k=f()
a=sorted(f())
INF=10**18+1
l,r=-INF,INF
while r-l>1:
  m=(l+r)//2
  s=0
  for i in a:
    li,ri=-1,n
    if i<0:
      while ri-li>1:
        mi=(li+ri)//2
        if i*a[mi]<m: ri=mi
        else: li=mi
      s+=n-ri
    else:
      while ri-li>1:
        mi=(li+ri)//2
        if i*a[mi]<m: li=mi
        else: ri=mi
      s+=ri
    if i*i<m: s-=1
  if s//2<k: l=m
  else: r=m
print(l)

### FIXED CODE ###

f=lambda:map(int,input().split())
n,k=f()
lm,lp=[],[]
for i in f():
  if i<0: lm.append(-i)
  else: lp.append(i)
lm.sort()
lp.sort()
cm=len(lm)
cp=len(lp)
def cnt(x):
  c=0
  if x<0:
    r=cp
    for i in lm:
      while r and i*lp[r-1]>=-x: r-=1
      c+=cp-r
    return c
  r=cm
  for i in lm:
    while r and i*lm[r-1]>x: r-=1
    c+=r
    if i*i<=x: c-=1
  r=cp
  for i in lp:
    while r and i*lp[r-1]>x: r-=1
    c+=r
    if i*i<=x: c-=1
  return cm*cp+c//2
INF=10**18+1
l,r=-INF,INF
while r-l>1:
  m=l+r>>1
  if cnt(m)<k: l=m
  else: r=m
print(r)
### BUGGY CODE ###

from collections import defaultdict
N, C = map(int, input().split())
dic = defaultdict(list)
for _ in range(N):
    s, t, c = input().split()
    dic[c].append([int(s), int(t)])
for c in dic:
    dic[c] = sorted(dic[c])
    l = len(dic[c])
    i = 0
    while i < l - 1:
        if i < l - 1 and dic[c][i][1] == dic[c][i + 1][0]:
            dic[c][i + 1][0] = dic[c][i][0]
            dic[c].pop(i)
            l -= 1
        else:
            i += 1
f = [0 for _ in range(10 ** 5 + 2)]
for c in dic:
    for t in dic[c]:
        f[t[0]] += 1
        f[t[1] + 1] -= 1

ans = 0
for i in range(1, 10 ** 5 + 1):
    f[i] += f[i - 1]
    if ans < f[i]:
        ans = f[i]
print(ans)

### FIXED CODE ###

import sys

def main():
    input = sys.stdin.readline
    N, C = map(int, input().split())
    dic = [[] for _ in range(C + 1)]
    for _ in range(N):
        s, t, c = input().split()
        dic[int(c)].append([int(s), int(t)])
    for c in range(C + 1):
        l = len(dic[c])
        if l == 1:
            continue
        dic[c] = sorted(dic[c])
        i = 0
        while i < l - 1:
            if i < l - 1 and dic[c][i][1] == dic[c][i + 1][0]:
                dic[c][i + 1][0] += 1
            else:
                i += 1
    f = [0 for _ in range(100002)]
    for c in range(C + 1):
        for t in dic[c]:
            f[t[0]] += 1
            f[t[1] + 1] -= 1
    ans = 0
    for i in range(1, 100001):
        f[i] += f[i - 1]
        if ans < f[i]:
            ans = f[i]
    print(ans)

if __name__ == "__main__":
    main()
### BUGGY CODE ###

from math import gcd
n=int(input())
a=list(map(int,input().split()))
x=[-1]*(10**6+5)
x[0]=0
x[1]=1
i=2
while i<=10**6+1:
    j=2*i
    if x[i]==-1:
        x[i]=i
        while j<=10**6+1:
            x[j]=i
            j+=i
    i+=1

z=[0]*(10**6+5)
def d(y):
    t=[]
    while y>=2:
        p=x[y]
        t.append(p)
        y=y//p
    t=list(set(t))
    for i in range(len(t)):
        z[t[i]]+=1
    return
g=gcd(a[0],a[0])
for i in range(n):
    g=gcd(g,a[i])
if g!=1:
    print("not coprime")
else:
    f=0
    for i in range(n):
        d(a[i])
    for i in range(10**6+1):
        if z[i]>=2:
            f=1
    print("pairwise coprime" if f==0 else "setwise coprime")


### FIXED CODE ###

from math import gcd
n=int(input())
a=list(map(int,input().split()))
x=[-1]*(10**6+5)
x[0]=0
x[1]=1
i=2
while i<=10**6+1:
    j=2*i
    if x[i]==-1:
        x[i]=i
        while j<=10**6+1:
            x[j]=i
            j+=i
    i+=1

z=[0]*(10**6+5)
def d(y):
    t=[]
    while y>=2:
        p=x[y]
        t.append(p)
        y=y//p
    t=list(set(t))
    for i in range(len(t)):
        z[t[i]]+=1
    return
g=gcd(a[0],a[0])
for i in range(n):
    g=gcd(g,a[i])
if g!=1:
    print("not coprime")
else:
    f=0
    for i in range(n):
        d(a[i])
    for i in range(10**6+1):
        if z[i]>=2:
            f=1
    print("pairwise coprime" if f==0 else "setwise coprime")
### BUGGY CODE ###

a,b=map(int,input().split())
print([_+y+z for _ in range(a+1) for y in range(a+1) for z in range(a+1)].count(b))

### FIXED CODE ###

k,s=map(int,input().split())
print(len([1 for z in range(k+1) for y in range(k+1) if 0<=s-y-z<=k]))
### BUGGY CODE ###

import networkx as nx

import io
import os


input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
edges = [[int(x) for x in input().split()] for i in range(M)]

# Will WA if you don't include nodes with no in/outdegrees
graph = nx.DiGraph()
for i in range(N):
    graph.add_node(i)
for u, v in edges:
    graph.add_edge(u, v)


SCC = list(nx.algorithms.components.strongly_connected_components(graph))
print(len(SCC))
for comp in reversed(SCC):
    print(len(comp), *comp)


### FIXED CODE ###

import io
import os


input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
edges = [[int(x) for x in input().split()] for i in range(M)]

from collections import defaultdict

graph = defaultdict(list)
for u, v in edges:
    graph[u].append(v)
    graph[v]

# https://atcoder.jp/contests/practice2/submissions/16566401
def scc(G):
    preorder = {}
    lowlink = {}
    seen = [False] * N
    scc_queue = []
    i = 0  # Preorder counter
    ans = []
    for source in range(N):
        if seen[source]:
            continue
        queue = [source]
        while queue:
            v = queue[-1]
            if v not in preorder:
                i = i + 1
                preorder[v] = i
            done = True
            for w in G[v]:
                if w not in preorder:
                    queue.append(w)
                    done = False
                    break
            if done:
                lowlink[v] = preorder[v]
                for w in G[v]:
                    if seen[w]:
                        continue
                    if preorder[w] > preorder[v]:
                        lowlink[v] = min([lowlink[v], lowlink[w]])
                    else:
                        lowlink[v] = min([lowlink[v], preorder[w]])
                queue.pop()
                if lowlink[v] == preorder[v]:
                    scc = {v}
                    seen[v] = True
                    while scc_queue and preorder[scc_queue[-1]] > preorder[v]:
                        k = scc_queue.pop()
                        scc.add(k)
                        seen[k] = True
                    ans.append(scc)
                else:
                    scc_queue.append(v)
    return ans


SCC = list(scc(graph))

DEBUG = False
print(len(SCC))
if DEBUG:
    seen = set()
for comp in reversed(SCC):
    print(len(comp), *comp)
    if DEBUG:
        for u in comp:
            for v in graph[u]:
                assert v not in seen
        seen.update(comp)
### BUGGY CODE ###

import sys
from math import cos, radians, pi, sqrt
import numpy as np

head = input().split()
N = int(head[0])
M = int(head[1])
inputs = [input() for i in range(M)]

i = 1
dic = {}
for i in range(0, M):
#	print("探索%d回目" % i)
	param = inputs[i].split()
	A = param[0]
	B = param[1]

	if A in dic.keys():
		dic[A].append(B)
	else:
		dic[A] = []
		dic[A].append(B)

	if B in dic.keys():
		dic[B].append(A)
	else:
		dic[B] = []
		dic[B].append(A)
	
depth = {'1': 0}
que = dic['1']
count=1

while not que == []:
	next_que = []
	for room in que:
		if room in depth.keys():
			continue

		depth[room] = count
		for next_room in dic[str(room)]:
			if not next_room in next_que:
				next_que.append(next_room)
	count += 1
	que = next_que

dist = {}
for i in range(1, N+1):
	for room, dep in depth.items():
		if depth[str(i)]-1 == dep:
			dist[str(i)] = room
			break

print("Yes")
for opt in dist.items():
	print(opt[1])


### FIXED CODE ###

n,m = map(int,input().split())
visited = [-1 for _ in range(n+1)]
visited[1] = 0
will = []
root = [[] for _ in range(n+1)] 
for i in range(m):
    a,b = map(int,input().split())
    root[a].append(b)
    root[b].append(a)

will.append(1)

while will:
    visit = will.pop(0)
    for i in root[visit]:
        if visited[i] != -1:
            continue
        will.append(i)
        visited[i] = visit

if visited[1:] == -1:
    print('No')
else:
    print('Yes')
    for i in range(2,len(visited)):
        print(visited[i])
### BUGGY CODE ###

n = int(input())
a = list(map(int, input().split()))
b = []
if n%2 == 0:
    for i in range(n):
        if i%2 == 0:
            b.append(a[i])
        else:
            b.insert(0,a[i])
else:
    for h in range(n):
        if h%2 == 0:
            b.insert(0,a[h])
        else:
            b.append(a[h])
print(*b)

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
o = [a[i] for i in range(2,n,2)]
e = [a[h] for h in range(1,n,2)]
if n%2 == 0:
    e.reverse()
    l = e + [a[0]] + o
    print(*l)
else:
    o.reverse()
    l = o + [a[0]] + e
    print(*l)
### BUGGY CODE ###

N,K=map(int,input().split())
P=list(map(int,input().split()))
E=[0]*N
for i,p in enumerate(P):
  for j in range(p):
    E[i]+=(j+1)/p
ans=sum(E[:K])
_=sum(E[:K])
for i in range(1,N-K+1):
  _-=E[i-1]
  _+=E[i+K-1]
  if _>ans:
    ans=_
print(ans)

### FIXED CODE ###

N,K=map(int,input().split())
P=list(map(int,input().split()))
E=[(p*(p+1)/2)/p for i,p in enumerate(P) ]
ans=sum(E[:K])
_=sum(E[:K])
for i in range(1,N-K+1):
  _-=E[i-1]
  _+=E[i+K-1]
  if _>ans:
    ans=_
print(ans)
### BUGGY CODE ###

# coding: utf-8
# Your code here!
import bisect
import sys
input=sys.stdin.readline
n=int(input())
d=list(map(int,input().split()))
m=int(input())
t=list(map(int,input().split()))
ans='NO'
d.sort()
for i in range(m):
    if d[bisect.bisect_right(d,t[i])-1]==t[i]:
        d.pop(bisect.bisect_right(d,t[i])-1)
        if i==m-1:
            ans='YES'
    else:
        break
print(ans)


### FIXED CODE ###

from collections import Counter
n=int(input())
d=list(map(int,input().split()))
m=int(input())
t=list(map(int,input().split()))

d_c=Counter(d)
t_c=Counter(t)
for i in t_c.keys():
    if t_c[i]>d_c[i]:
        print('NO')
        exit()
print('YES')
### BUGGY CODE ###

T = input()
 
w0 = "dream"
w1 = "dreamer"
w2 = "erase"
w3 = "eraser"
 
dict_sen = {0:w0,1:w1,2:w2,3:w3}
 
dp = ""
 
while(len(dp) < len(T)):
  for i in range(4):
    if T[:len(dict_sen[i])] == dict_sen[i]:
      T = T[len(dict_sen):]
      dp = dp + dict_sen[i]
      break
if dp == T :
  print("YES")
else :
  print("NO")

### FIXED CODE ###

S=str(input()) #Sの入力
Smojisuu=len(S)
c=S.count("eraser")
S=S.replace("eraser","xxxxxx",c)
d=S.count("erase")
S=S.replace("erase","xxxxx",d)
e=S.count("dreamer")
S=S.replace("dreamer","xxxxxxx",e)
f=S.count("dream")
S=S.replace("dream","xxxxx",f)
g=S.count("x")
if len(S)>g:
  print("NO")
elif len(S)==g:
  print("YES")
else:
  print("error")
### BUGGY CODE ###

n = int(input())
s = input()

result = set()
for i in range(1000):
    v = str(i).zfill(3)
    key = []
    p = -1
    for j in range(3):
        for k in range(n):
            if v[j] == s[k] and k > p:
                key.append(s[k])
                p = k
                break
    if len(key) == 3:
        result.add(''.join(key))

print(len(result))

### FIXED CODE ###

n = int(input())
s = list(map(int, input()))

ans = 0
for i in range(10):
    if i in s[: n - 2]:
        x = s.index(i)
        for j in range(10):
            if j in s[x + 1: n - 1]:
                y = x + 1 + s[x + 1: n - 1].index(j)
                for k in range(10):
                    if k in s[y + 1:]:
                        ans += 1
print(ans)
### BUGGY CODE ###

# -*- coding: utf-8 -*-

import sys
import math
from decimal import Decimal, ROUND_DOWN
from collections import deque
from itertools import combinations
import copy

debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        for line in sys.stdin:
            lines.append(line.strip())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]

    (n, ) = [int(e) for e in lines[0].split(' ')]
    a = [int(e) for e in lines[1].split(' ')]


    return (n, a)


def solve(n, a):

   
    total = 0
    m = int(10**9 + 7)
    for i in range(n-1):
        for j in range(i+1, n):
            tmp = (a[i] * a[j]) % m
            total = (total + tmp) % m
            


    return total
    


def main():
    # 出力
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r, sep='')
    else:
        print("%s" % result, sep='')

if __name__ == '__main__':

    main()
	


### FIXED CODE ###

# -*- coding: utf-8 -*-

import sys
import math
from decimal import Decimal, ROUND_DOWN
from collections import deque
from itertools import combinations
import copy

debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        for line in sys.stdin:
            lines.append(line.strip())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]

    (n, ) = [int(e) for e in lines[0].split(' ')]
    a = [int(e) for e in lines[1].split(' ')]


    return (n, a)


def solve(n, a):

   
    total = 0
    m = int(10**9 + 7)
    s = sum(a)
    s_current = 0
    for i in range(n):
        s_current = s_current + a[i]
        total = (total + a[i] * (s - s_current)) % m

    total = total % m


    return total
    


def main():
    # 出力
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r, sep='')
    else:
        print("%s" % result, sep='')

if __name__ == '__main__':

    main()
### BUGGY CODE ###

N = int(input())
ans = 0
for i in range(N+1):
    nums = list(str(i))
    cnt_3 = 0
    cnt_5 = 0
    cnt_7 = 0
    can_answer = True
    for j in range(len(nums)):
        if nums[j] == '3':
            cnt_3 += 1
        elif nums[j] == '5':
            cnt_5 += 1
        elif nums[j] == '7':
            cnt_7 += 1
        else:
            can_answer = False

    if can_answer and cnt_3 > 0 and cnt_5 > 0 and cnt_7 > 0:
        ans += 1
print(ans)


### FIXED CODE ###

N = int(input())


def dfs(s):
    if int(s) > N:
        return 0
    if s == '0':
        s = ''
    ret = 0
    if all(s.count(c) > 0 for c in '753'):
        ret += 1
    for c in '753':
        ret += dfs(c + s)
    return ret


print(dfs('0'))
### BUGGY CODE ###

n = int(input())
mentors = input().split(" ")
mentors = [int(mentors[i]) for i in range(len(mentors))] 

for i in range(1, n+1):
    print(mentors.count(i))

### FIXED CODE ###

import collections

n = int(input())
mentors = input().split(" ")

a = collections.Counter(mentors)

for i in range(1, n+1):
    if str(i) in a.keys():
        print(a[str(i)])
    else:
        print(0)
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))
ans = 0
mod = 10**9+7
for i in range(n):
  for j in range(i+1,n):
    ans += (a[i]*a[j])%mod
    
print(ans%mod)

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
arr = [0]*(n+1)
ans = 0
mod = 10**9+7
for i in range(n):
  arr[i+1] += arr[i]+a[i]
  
for i in range(n):
  ans += (a[i]*(arr[n]-arr[i+1]))%mod
print(ans%mod)
### BUGGY CODE ###

N,M=map(int,input().split())
a=[]
for i in range(M):
   a.append(int(input()))
dp=[0]*(N+1)
dp[0]=1
if 1 not in a:
    dp[1]=1
for i in range(2,N+1):
    if i in a:
        continue
    dp[i]=(dp[i-1]+dp[i-2])
print(dp[-1]%1000000007)    

### FIXED CODE ###

N,M=map(int,input().split())
dp=[1]*(N+1)
for i in range(M):
    dp[int(input())]=0
for i in range(2,N+1):
    if dp[i]!=0:
        dp[i]=(dp[i-1]+dp[i-2])
print(dp[-1]%1000000007)
### BUGGY CODE ###

N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
# M:カードの数字の最大値+1
M = max(max(A),max(B))+1

INF = float('inf')
# dp[mask][a]:maskのカードが操作済で、そのうち右端のカードの数字がaであるときの操作回数の最小値
dp = [[INF for _ in range(M)] for _ in range(1<<N)]
dp[0][0] = 0

for i in range(1<<N):
  # idx:操作済カードの枚数
  idx = 0
  for k in range(N):
    if (i>>k)&1 == 1:
      idx += 1
  for j in range(M):
    if dp[i][j] >= INF:
      continue
    for k in range(N):
      # k:右端の操作済カードの次に来るカード
      # kがすでに操作済の場合はcontinueする
      if i&(1<<k) == 1:
        continue
      
      # kが何回操作されるかによってkの数字が表の数字になるか裏の数字になるかが決まる
      if abs(k-idx)%2 == 0:
        c = A[k]
      else:
        c = B[k]

      # kの数字広義単調増加にならない場合はcontinue
      if j > c:
        continue
      
      # t:kを右端の操作済カードの次に並べるための操作回数
      # それは、初期配置でkより左にあってまだ操作済でないカードの枚数と一致する
      t = 0
      for l in range(k):
        if (i>>l)&1 == 0:
          t += 1
      #print(i,k,idx,c,dp[i|(1<<k)][c],t)
      dp[i|(1<<k)][c] = min(dp[i|(1<<k)][c],dp[i][j]+t)

#print(dp)
ans = INF
for i in range(M):
  ans = min(dp[(1<<N)-1][i],ans)
print(ans if ans < INF else -1)

### FIXED CODE ###

def main():
  N = int(input())
  A = list(map(int,input().split()))
  B = list(map(int,input().split()))
  # M:カードの数字の最大値+1
  M = max(max(A),max(B))+1
  
  INF = float('inf')
  # dp[mask][a]:maskのカードが操作済で、そのうち右端のカードの数字がaであるときの操作回数の最小値
  dp = [[INF for _ in range(M)] for _ in range(1<<N)]
  dp[0][0] = 0
  
  for i in range(1<<N):
    # idx:操作済カードの枚数
    idx = 0
    for k in range(N):
      if (i>>k)&1 == 1:
        idx += 1
    for j in range(M):
      if dp[i][j] >= INF:
        continue
      for k in range(N):
        # k:右端の操作済カードの次に来るカード
        # kがすでに操作済の場合はcontinueする
        if i&(1<<k) == 1:
          continue
        
        # kが何回操作されるかによってkの数字が表の数字になるか裏の数字になるかが決まる
        if abs(k-idx)%2 == 0:
          c = A[k]
        else:
          c = B[k]
  
        # kの数字広義単調増加にならない場合はcontinue
        if j > c:
          continue
        
        # t:kを右端の操作済カードの次に並べるための操作回数
        # それは、初期配置でkより左にあってまだ操作済でないカードの枚数と一致する
        t = 0
        for l in range(k):
          if (i>>l)&1 == 0:
            t += 1
        #print(i,k,idx,c,dp[i|(1<<k)][c],t)
        dp[i|(1<<k)][c] = min(dp[i|(1<<k)][c],dp[i][j]+t)
  
  #print(dp)
  ans = INF
  for i in range(M):
    ans = min(dp[(1<<N)-1][i],ans)
  print(ans if ans < INF else -1)

if __name__ == '__main__':
  main()
### BUGGY CODE ###

s = list(input())
q = int(input())
q_lists = [input().split() for _ in range(q)]
hanten = 0
for i in q_lists:
    if len(i)==1:
        hanten += 1
    else:
        f = i[1]
        c = i[2]
        if hanten%2==0:
            if f=='1':
                s =[c] + s
            else:
                s.append(c)
        else:
            if f=="1":
                s.append(c)
            else:
                s = [c] + s
print(''.join(s) if hanten%2==0 else ''.join(s[::-1]))        

### FIXED CODE ###

s = input()
q = int(input())
ans_list1 = []
ans_list2 = []
flag = 1
for i in range(q):
    i = input().split()
    if i[0]=="1":
        flag *= -1
    else:
        if i[1]=='1':
            if flag==1:
                ans_list1.append(i[2])
            else:
                ans_list2.append(i[2])
        else:
            if flag==1:
                ans_list2.append(i[2])
            else:
                ans_list1.append(i[2])

if flag==1:
    print(''.join(ans_list1[::-1]) + s +''.join(ans_list2))
else:
    print(''.join(ans_list2[::-1]) + s[::-1] +''.join(ans_list1))