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

s = input()
q = int(input())

for i in range(q):
  order = list(input().split())
  if order[0] == '1':
    s = s[::-1]
  elif order[1] == '1':
    s = order[2] + s
  elif order[1] == '2':
    s = s + order[2]
print(s)

### FIXED CODE ###

s = input()
q = int(input())
 
head = []
tail = []
flip = 0
 
for i in range(q):
    query = input().split()
    if query[0] == "1":
        flip ^=1
    else:
        f = int(query[1]) - 1
        c = query[2]
        if (f ^ flip) == 0:
            head.append(c)
        else:
            tail.append(c)
 
if flip:
    head, tail = tail, head
    s = s[::-1]
 
head = "".join(head)
tail = "".join(tail)
 
print(head[::-1] + s + tail)
### BUGGY CODE ###

# D - Knapsack Queries on a tree

from sys import stdin
import bisect

n = int(stdin.readline())

v = [0] * n
w = [0] * n
for i in range(n):
    v[i], w[i] = map(int, stdin.readline().split())

max_l = 10 ** 5

# dp table (for some amount)
dp = [None] * min(n, 2 ** 14)

# dp[vertex] = list of (weight, value)
dp[0] = [(0, 0), (w[0], v[0])]

for u in range(1, len(dp)):
    parent = (u - 1) // 2

    dp[u] = dp[parent].copy()
    for ww, vv in dp[parent]:
        dp[u].append((ww + w[u], vv + v[u]))
    dp[u].sort()

    # remove unnecessary entries
    tail = 0
    for i in range(1, len(dp[u])):
        if dp[u][i][0] > max_l:
            break
        if dp[u][tail][1] < dp[u][i][1]:
            tail += 1
            dp[u][tail] = dp[u][i]
    del dp[u][tail + 1:]

dpw = [None] * len(dp)

def solve(u, l):
    if u < len(dp):
        if not dpw[u]:
            dpw[u] = [w for w, v in dp[u]]
        x = bisect.bisect_right(dpw[u], l) - 1
        return dp[u][x][1]

    parent = (u - 1) // 2
    s = solve(parent, l)
    if l >= w[u]:
        s = max(s, v[u] + solve(parent, l - w[u]))
    return s

q = int(stdin.readline())
for i in range(q):
    u, l = map(int, stdin.readline().split())
    print(solve(u - 1, l))


### FIXED CODE ###

# D - Knapsack Queries on a tree

from sys import stdin
import bisect

readline = stdin.readline
bisect_right = bisect.bisect_right

n = int(readline())

v = [0] * n
w = [0] * n
for i in range(n):
    v[i], w[i] = map(int, readline().split())

max_l = 10 ** 5
vshift = 21
mask = (1 << vshift) - 1

# dp table (for some amount)
dp = [None] * min(n, 2 ** 12)

# dp[vertex] = list of (weight, value)
dp[0] = [(0 << vshift) + 0, (w[0] << vshift) + v[0]]

for u in range(1, len(dp)):
    parent = (u - 1) // 2

    ls = dp[parent][:]
    ls.extend(x + (w[u] << vshift) + v[u] for x in dp[parent]
              if (x >> vshift) + w[u] <= max_l)
    ls.sort()

    # remove unnecessary entries
    tail = 0
    for i in range(1, len(ls)):
        if (ls[tail] >> vshift) == (ls[i] >> vshift):
            ls[tail] = ls[i]
        elif (ls[tail] & mask) < (ls[i] & mask):
            tail += 1
            ls[tail] = ls[i]
    del ls[tail + 1:]
    dp[u] = ls

def solve(u, l):
    if u < len(dp):
        x = bisect_right(dp[u], (l << vshift) + mask) - 1
        return dp[u][x] & mask

    parent = (u - 1) // 2
    s = solve(parent, l)
    if l >= w[u]:
        s = max(s, v[u] + solve(parent, l - w[u]))
    return s

q = int(readline())
for i in range(q):
    u, l = map(int, readline().split())
    print(solve(u - 1, l))
### BUGGY CODE ###

X = int(input())

c = []
for i in range(-(X+1), X+1):
    if i != 0 and X % i == 0:
        c.append([i, X//i])

for x1, x2 in c:
    for b in range(-1000, 1000):
        if b != 0:
            if (x1+b)**4 + ((x1+b)**3)*b + ((x1+b)**2)*(b**2) + (x1+b)*(b**3) + b**4 == x2:
                print(x1+b, b)
                break

### FIXED CODE ###

X = int(input())

c = []
for i in range(1, int((X+1)**(1/2))+1):
    if i != 0 and X % i == 0:
        c.append([i, X//i])

for x1, x2 in c:
    for b in range(-1000, 1000):
        if b != 0:
            if (x1+b)**3 * (2*b+x1) + (b**2) * (x1**2 + 3*x1*b+3*(b**2)) == x2:
                print(x1+b, b)
                break
### BUGGY CODE ###

### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

sys.setrecursionlimit(100000000)

def yn(b):
    print("Yes" if b==1 else "No")
    return

def xxx(t,memo,ans,kyori):
    for a in memo[t]:
        if ans[a] == -1 or kyori[a] > (kyori[t]+1):
            ans[a]=t
            kyori[a]=kyori[t]+1
            xxx(a,memo,ans,kyori)


def resolve():
    readline=sys.stdin.readline

    n,m=map(int, readline().rstrip().split())
    memo=[[] for i in range(n)]
    ans=[-1]*n
    kyori=[-1]*n
    ans[0]=0
    kyori[0]=0
    for i in range(m):
        a,b=map(int, readline().rstrip().split())
        memo[a-1].append(b-1)
        memo[b-1].append(a-1)
    xxx(0,memo,ans,kyori)
    #tt=[0]
    #nx=[]
    #for t in tt:
    #    for a in memo[t]:
    #        if ans[a]
        
    #memo

    if -1 in ans:
        print("No")
    else:
        print("Yes")
        for i in range(1,n):
            print(ans[i]+1)


    #arr=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------


### FIXED CODE ###

### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

sys.setrecursionlimit(100000000)

def yn(b):
    print("Yes" if b==1 else "No")
    return

def xxx(t,memo,ans,kyori):
    for a in memo[t]:
        if ans[a] == -1 or kyori[a] > (kyori[t]+1):
            ans[a]=t
            kyori[a]=kyori[t]+1
            xxx(a,memo,ans,kyori)


def resolve():
    readline=sys.stdin.readline

    n,m=map(int, readline().rstrip().split())
    memo=[[] for i in range(n)]
    ans=[-1]*n
    kyori=[-1]*n
    ans[0]=0
    kyori[0]=0
    for i in range(m):
        a,b=map(int, readline().rstrip().split())
        memo[a-1].append(b-1)
        memo[b-1].append(a-1)
    #xxx(0,memo,ans,kyori)
    tt=[0]
    while 1:
        nx=[]
        for t in tt:
            for a in memo[t]:
                if ans[a] == -1 or kyori[a] > (kyori[t]+1):
                    nx.append(a)
                    ans[a]=t
                    kyori[a]=kyori[t]+1
        if len(nx)==0:
            break
        else:
            tt=nx
        
    #memo

    if -1 in ans:
        print("No")
    else:
        print("Yes")
        for i in range(1,n):
            print(ans[i]+1)


    #arr=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------
### BUGGY CODE ###

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

diff, diffm = 0,0

for i in range(len(A)-1):

  diff = max(A[i:]) - A[i]

  if diff > diffm: diffm = diff

print(diffm)

### FIXED CODE ###

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

total, large = 0,0

for i in A:
  
  if large > i:
    total += (large - i)
  
  if i > large: large = i
    
print(total)
### BUGGY CODE ###

#左からn個目でendが特定の色の場合に
N,M,K = list(map(int,input().split()))

def xgcd(a, b):
  x0, y0, x1, y1 = 1, 0, 0, 1
  while b != 0:
    q, a, b = a // b, b, a % b
    x0, x1 = x1, x0 - q * x1
    y0, y1 = y1, y0 - q * y1
  return a, x0, y0
def modinv(a, m):
  g, x, y = xgcd(a, m)
  if g != 1:
    raise Exception('modular inverse does not exist')
  else:
    return x % m
def combination(n, k, mod=1e9+7) -> int:
  ret = 1
  for i in range(1, k+1):
    ret = (ret * (n-k+i) * modinv(i, mod))%mod
  return int(ret)

def pow(base, exponent, mod=1e9+7) -> int:
  if exponent == 0:
    return 1
  if exponent > 1:
    d,m = divmod(exponent, 2)
    return (base**m * pow(base, d, mod)**2 ) % mod
  else:
    return base

m = 998244353
res = 0
B = 1
for k in range(K+1):
  A = M * pow(M-1,N-k-1,m)
  if k>0:
    B = B*(N-k)//k 
  res = (res+ A*B)%m
print (res)

### FIXED CODE ###

#左からn個目でendが特定の色の場合に
N,M,K = list(map(int,input().split()))

def xgcd(a, b):
  x0, y0, x1, y1 = 1, 0, 0, 1
  while b != 0:
    q, a, b = a // b, b, a % b
    x0, x1 = x1, x0 - q * x1
    y0, y1 = y1, y0 - q * y1
  return a, x0, y0
def modinv(a, m):
  g, x, y = xgcd(a, m)
  if g != 1:
    raise Exception('modular inverse does not exist')
  else:
    return x % m
def combination(n, k, mod=1e9+7) -> int:
  ret = 1
  for i in range(1, k+1):
    ret = (ret * (n-k+i) * modinv(i, mod))%mod
  return int(ret)

def pow(base, exponent, mod=1e9+7) -> int:
  if exponent == 0:
    return 1
  if exponent > 1:
    d,m = divmod(exponent, 2)
    return (base**m * pow(base, d, mod)**2 ) % mod
  else:
    return base

m = 998244353
res = 0
B = 1
if M != 1:
  mi = modinv(M-1,m)
  A = M * pow(M-1,N-1,m)
  for k in range(K+1):
    if k>0:
      B = (B*(N-k)*modinv(k,m))%m
    res = (res+ A*B)%m
    A = (A*mi)%m
  print (res)
else:
  if K == N-1:
    
    print(1)
  else:
    print(0)
### BUGGY CODE ###

h,w,a,b=[int(i) for i in input().split()]
p=10**9+7
def kai(n):
  a=1
  for i in range(1,n+1):
    a*=i
    a%=p
  return a
def conv(k,n):
  a=kai(n)*pow(kai(k),p-2,p)*pow(kai(n-k),p-2,p)
  return a%p
ans=0
for i in range(b+1,w+1):
  ans+=conv(i-1,i+h-a-2)*conv(w-i,a+w-i-1)
  ans%=p
print(ans)

### FIXED CODE ###

h, w, a, b = [int(i) for i in input().split()]

mod = 10 ** 9 + 7
kkai = [1]
for i in range(1, 210000):
    kkai.append(kkai[-1] * i % mod)


def kai(x, p=mod):
    return kkai[x]


def comb(a, b, p=mod):
    if a < 0 or b < 0:
        return 0
    elif a < b:
        return 0
    c = 1
    c *= kai(a, p)
    c *= pow(kai(b, p), p - 2, p)
    c *= pow(kai(a - b, p), p - 2, p)
    return c % p


ans = 0
for i in range(b, w):
    ans += comb(i+(h-a)-1, i)*comb((w-i)+a-2, a-1)
    ans %= mod
print(ans)
### BUGGY CODE ###

from itertools import permutations
import sys, re
inp = sys.stdin.readline().strip()
perms = []
used = []
total = 0
#orig = inp

def checkOrder(check, inp):
    count = 0
    for i in range(len(check)):
        if check[i] == '+':
            continue
        elif check[i] == inp[count]:
            count += 1
        else:
            return False
    return True


for i in range(0, len(inp)):
    withPlus = inp + '+' * i
    perms = [''.join(p) for p in permutations(withPlus)]

    for perm in perms:
        if not re.match(r'.*\+\+.*', perm) and not perm[0] == '+' and not perm[-1] == '+':
            if checkOrder(perm, inp) and not perm in used:
                total += eval(perm)
                used.append(perm)

print(total)


### FIXED CODE ###

import sys
perm = sys.stdin.readline().strip()
total = 0

# Add n * '+' to inp
def addPlus(inp, n):
    total = 0
    possible = [inp]
    orig = inp

    for i in range(1, len(orig)):
        possible.append(orig[:i] + '+' + perm[i:])

    for i in range(1, n):
        curr = possible[:]
        for item in curr:
            for j in range(1, len(item)):
                processed = item[:j] + '+' + item[j:]
                if processed not in possible:
                    if '++' not in processed:
                        possible.append(processed)

    for item in possible:
        total += eval(item)

    return total


print(addPlus(perm, len(perm) - 1))
### BUGGY CODE ###

import sys
from collections import deque

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


N, M = MI()

nl = [list() for _ in range(N + 1)]
rev = [list() for _ in range(N + 1)]
for _ in range(N - 1 + M):
    A, B = MI()
    nl[A].append(B)
    rev[B].append(A)

for i, l in enumerate(rev):
    if i > 0 and len(l) == 0:
        root = i
        break

ans = [-1] * (N + 1)
q = deque([(root, 0)])
while len(q) > 0:
    v, p = q.popleft()
    ans[v] = p
    for next_v in nl[v]:
        q.append((next_v, v))

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

### FIXED CODE ###

import sys

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


N, M = MI()

nl = [list() for _ in range(N + 1)]
rev = [list() for _ in range(N + 1)]
deg = [0 for _ in range(N + 1)]
for _ in range(N - 1 + M):
    A, B = MI()
    nl[A].append(B)
    rev[B].append(A)
    deg[B] += 1

for i, l in enumerate(deg):
    if i > 0 and l == 0:
        root = i
        break

stack = [root]
tsorted = list()
while len(stack) > 0:
    v = stack.pop()
    tsorted.append(v)
    for next_v in nl[v]:
        deg[next_v] -= 1
        if deg[next_v] == 0:
            stack.append(next_v)

ans = [0] * (N + 1)
p = {root: 0}
for v in tsorted:
    ans[v] = p[v]
    for next_v in nl[v]:
        p[next_v] = v
for a in ans[1:]:
    print(a)
### BUGGY CODE ###

MOD = 1000000007


def egcd(a, b):
    (x, lastx) = (0, 1)
    (y, lasty) = (1, 0)
    while b != 0:
        q = a // b
        (a, b) = (b, a % b)
        (x, lastx) = (lastx - q * x, x)
        (y, lasty) = (lasty - q * y, y)
    return (lastx, lasty, a)

def modinv(a, m):
    (inv, q, gcd_val) = egcd(a, m)
    return inv % m

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
x = [[] for _ in range(n)]
y = [[] for _ in range(n)]
z = 1
x[0] += [a[0]]
y[n-1] += [b[n-1]]



for i in range(1,n):
    if a[i-1]<a[i]:
        x[i] += [a[i]]
    else:
        x[i] += list(range(1,a[i]+1))

for j in range(n-1, 0, -1):
    if b[j-1]>b[j]:
        y[j-1] += [b[j-1]]
    else:
        y[j-1] += list(range(1,b[j-1]+1))

for i in range(0,n):
    z *= len(set(x[i])&set(y[i])) % MOD
    z = z % MOD 

print(z)


### FIXED CODE ###

import sys

MOD = 1000000007

def union(x,y):
    if len(x)==1:
        if len(y)==1:
            return (1 if x[0]==y[0] else 0)
        else:
            return (1 if y[-1]>=x[0] else 0)
    if len(x)>1:
        if len(y)==1:
            return (1 if x[-1]>=y[0] else 0)
        else:
            return min(len(x),len(y))

n = int(input())
a = list(map(lambda x: int(x) % MOD, input().split()))
b = list(map(lambda x: int(x) % MOD, input().split()))
x = [0 for _ in range(n)]
y = [0 for _ in range(n)]
x[0] = 1
y[-1] = 1
z = 1

for i in range(1,n):
    if a[i-1]<a[i]:
        x[i] = 1
    else:
        x[i] = 0

for j in range(n-1, 0, -1):
    if b[j-1]>b[j]:
        y[j-1] += 1
    else:
        y[j-1] += 0

for i in range(n):
    if x[i] == 1 and y[i] == 0:
        if a[i] > b[i]:
            print(0)
            sys.exit()
    elif x[i] == 0 and y[i] == 1:
        if a[i] < b[i]:
            print(0)
            sys.exit()
    elif x[i] == 1 and y[i] == 1:
        if a[i] != b[i]:
            print(0)
            sys.exit()
    else:
        z *= min(a[i],b[i])
        z = z % MOD

print(z)
### BUGGY CODE ###

from queue import PriorityQueue
from collections import defaultdict

n, m, s = map(int, input().split())
graph = defaultdict(dict)
for i in range(m):
    u, v, a, b = map(int, input().split())
    graph[u][v] = (a, b)
    graph[v][u] = (a, b)

town = [None]*(n+1)
for i in range(n):
    c, d = map(int, input().split())
    town[i+1] = (c, d)

if s >= 2501:
    s = 2501
x = (1, s)
cost = 0
visit = set()
pq = PriorityQueue()
pq.put((cost, x))
ans = [1000000000000000]*(n+1)
while not pq.empty():
    cost, x = pq.get()
    if x in visit:
        continue
    visit.add(x)
    p, m = x
    ans[p] = min(ans[p], cost)
    c, d = town[p]
    if m <= 2501:
        pq.put((cost+d, (p, m+c)))
    for q, edge in graph[p].items():
        a, b = edge
        if m-a >= 0:
            pq.put((cost+b, (q, m-a)))
for i in range(2, n+1):
    print(ans[i])

### FIXED CODE ###

from queue import PriorityQueue
from collections import defaultdict
from heapq import heappush, heappop

n, m, s = map(int, input().split())
graph = defaultdict(dict)
for i in range(m):
    u, v, a, b = map(int, input().split())
    graph[u][v] = (a, b)
    graph[v][u] = (a, b)

town = [None]*(n+1)
for i in range(n):
    c, d = map(int, input().split())
    town[i+1] = (c, d)

if s >= 2501:
    s = 2501
x = (1, s)
cost = 0
visit = set()
heap = []
heappush(heap, (cost, x))
ans = [None]*(n+1)
check = 0
while len(heap) > 0:
    cost, x = heappop(heap)
    if x in visit:
        continue
    visit.add(x)
    p, m = x
    if ans[p] is None:
        ans[p] = cost
        check += 1
        if check >= n:
            break
    c, d = town[p]
    if m <= 2501:
        heappush(heap, (cost+d, (p, m+c)))
    for q, edge in graph[p].items():
        a, b = edge
        if m-a >= 0:
            heappush(heap, (cost+b, (q, m-a)))
for i in range(2, n+1):
    print(ans[i])
### BUGGY CODE ###

n,m = map(int,input().split())
ab = [list(map(int, input().split())) for i in range(n)]
ab = sorted(ab)
income = 0
day = 1 #残り日数
i = 0
list1 = []

while (day <= m):
  if i <= n-1:
    if (ab[i][0] <= day):
      list1.append(ab[i])
      i += 1 
    else:
      day += 1
      if list1 != []:
        p = max(list1, key = lambda x:x[1])
        income += p[1]
        list1.pop(list1.index(p))
      #print(day,i,income)
  else:
    day += 1
    if list1 != []:
      p = max(list1, key = lambda x:x[1])
      income += p[1]
      list1.pop(list1.index(p))
      
print(income)

### FIXED CODE ###

from heapq import heappop, heappush 
N, M = map(int, input().split())
score = 0
AB = [[] for i in range(M)]
for i in range(N):
  a, b = map(int, input().split())
  if M - a >= 0:
    AB[M - a].append(b)
  
#print(AB)
queue = []
for i in range(1, M + 1):
  for j in AB[-i]:
    heappush(queue, -j)
  if queue != []:
    score += -1 * heappop(queue)
  
  #print(score, queue)  
print(score)
### BUGGY CODE ###

n=int(input())
A=list(map(int,input().split()))
ans=0
for i in range(min(A)-1,max(A)+2):
    x=0
    for a in A:
        if a-1==i or a==i or a+1==i:
            x+=1
    ans=max(ans,x)
print(ans)
    

### FIXED CODE ###

n=int(input())
A=list(map(int,input().split()))
D=[0 for i in range(10**7)]
for a in A:
    D[a-1]+=1
    D[a]+=1
    D[a+1]+=1
print(max(D))
### BUGGY CODE ###

from functools import reduce
from operator import mul

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

p_score = reduce(mul, a[:k])
scores = [p_score]
for i in range(k, n):
    score = scores[-1]/a[i-k]*a[i]
    scores.append(score)
for i in range(1, len(scores)):
    if scores[i] > scores[i-1]:
        print("Yes")
    else:
        print("No")


### FIXED CODE ###

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

answers = []
for i in range(k, n):
    answers.append(a[i-k] < a[i])
for ans in answers:
    if ans:
        print("Yes")
    else:
        print("No")
### BUGGY CODE ###

import functools

# 最大公約数
def gcd(m, n):
    r = m % n
    return gcd(n, r) if r else n

def gcd_list(nums):
    return functools.reduce(gcd, nums)

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

# i番目を取り去る
ans = 0
for i in range(N):
    tmp_left = A[:i]
    tmp_right = A[i+1:]
    tmp_lr = tmp_left + tmp_right
    tmp = gcd_list(tmp_lr)
    ans = max(ans,tmp)
print(ans)

### FIXED CODE ###

import fractions

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

left = [0]*(N+1)
right = [0]*(N+1)
for i in range(N):
    left[i+1] = (fractions.gcd(left[i],A[i]))
    right[N-i-1] = fractions.gcd(right[N-i],A[N-1-i])

ans = 0
for i in range(N):
    ans = max(ans,fractions.gcd(left[i],right[i+1]))
print(ans)
### BUGGY CODE ###

x,y,aa,bb,cc = map(int,raw_input().split(' '))

aas = map(int, raw_input().split(' '))
bbs = map(int, raw_input().split(' '))
ccs = map(int, raw_input().split(' '))
aas.sort(key = lambda x:-x)
bbs.sort(key = lambda x:-x)
ccs.sort(key = lambda x:-x)

for i in range(1,len(aas)): aas[i] += aas[i-1]
for i in range(1,len(bbs)): bbs[i] += bbs[i-1]
for i in range(1,len(ccs)): ccs[i] += ccs[i-1]


r = 0

for a in range(x + 1):
	for b in range(y + 1)[::-1]:
		m = (aas[a-1] if a-1 >= 0 else 0) + (bbs[b-1] if b-1 >=0 else 0)
		c = x + y - (a + b)
		if c == 0:
			m += 0
		elif c > 0 and c-1 < len(ccs): 	 	
			m += ccs[c-1]
		else: 
			m+= -float('inf')
			break
		r = max(r, m)

print r


### FIXED CODE ###

import collections
x,y,aa,bb,cc = map(int,raw_input().split(' '))

aas = map(int, raw_input().split(' '))
bbs = map(int, raw_input().split(' '))
ccs = map(int, raw_input().split(' '))

aas.sort(key = lambda x:-x)
bbs.sort(key = lambda x:-x)
ccs.sort(key = lambda x:-x)
aas = aas[:x]
bbs = bbs[:y]

r = (aas + bbs)
r.sort()

i = 0
j = 0
while(j < len(ccs) and i < len(r)):
	if ccs[j] > r[i]:
		r[i] = ccs[j]
		i+=1
	j+=1

print sum(r)
### BUGGY CODE ###

import numpy as np

K = int(input())
result = 0

for a in range(1, K+1):
  for b in range(1, K+1):
    temp = np.gcd.reduce([a, b])
    for c in range(1, K+1):
      result += np.gcd.reduce([temp, c])

print(result)

### FIXED CODE ###

import math

K = int(input())
result = 0

for a in range(1, K+1):
  for b in range(1, K+1):
    temp = math.gcd(a, b)
    for c in range(1, K+1):
      result += math.gcd(temp, c)

print(result)
### BUGGY CODE ###

def main():
    import sys
    input = sys.stdin.readline
    #区間の管理は　[a, b)で管理していることに注意

    # INT_MIN = -10 ** 18
    MAX_N = 4 * 10 ** 5
    # MAX_N = 20


    def init(n_):
        #簡単にするために2のべき乗に揃える
        n = 1
        while n < n_:
            n *= 2
        return n

    #初期化
    N = int(input())
    n = init(N)
    data = [0] * (2 * MAX_N - 1)

    def update(k, a):
        k += n - 1
        data[k] = a
        while k > 0:
            k = (k - 1) // 2
            data[k] = max(data[2 * k + 1], data[2 * k + 2])

    def query(a, b, k = 0, l = 0, r = n):
        if r <= a or b <= l:
            return 0
        if a <= l and r <= b:
            return data[k]
        else:
            v1 = query(a, b, 2 * k + 1, l, (l + r)//2)
            v2 = query(a, b, 2 * k + 2, (l + r)//2, r)
            return max(v1, v2)

    H = tuple(map(int, input().split()))
    A = tuple(map(int, input().split()))

    ans = 0
    for i in range(N):
        # h = int(input())
        # a = int(input())
        h = H[i]
        a = A[i]
        tmp = query(1, h + 1) #[1, h)での最大値
        # print (h, tmp)
        update(h, tmp + a)
        ans = max(ans, tmp + a)
        # print (data)

    print (ans)

    # print (update(1, 1))
    # print (update(2, 5))
    # print (query(1, 2))

if __name__ == '__main__':
    main()

### FIXED CODE ###

def main():
    import sys
    input = sys.stdin.readline
    #区間の管理は　[a, b)で管理していることに注意

    # INT_MIN = -10 ** 18
    # MAX_N = 4 * 10 ** 5
    # MAX_N = 20


    # def init(n_):
    #     #簡単にするために2のべき乗に揃える
    #     n = 1
    #     while n <= n_:
    #         n *= 2
    #     return n

    #初期化
    N = int(input())
    # n = 1
    # while n <= N:
    #     n *= 2

    n = 262144
    data = [0] * (2 * n - 1)

    def update(k, a):
        k = k + n - 1
        # data[k] = a
        while k >= 0:
            data[k] = max(a, data[k])
            k = (k - 1) // 2
            # data[k] = max(data[2 * k + 1], data[2 * k + 2])

    def query(a, b, k, l, r):
        if r <= a or b <= l:
            return 0
        elif a <= l and r <= b:
            return data[k]
        else:
            return max(query(a, b, 2 * k + 1, l, (l + r)//2), query(a, b, 2 * k + 2, (l + r)//2, r))

    H = tuple(map(int, input().split()))
    A = tuple(map(int, input().split()))

    # ans = 0

    dp = [A[0]] + [0] * (N - 1)
    update(H[0] - 1, A[0])
    for i in range(1, N):
        # h = int(input())
        # a = int(input())
        dp[i] = query(0, H[i] - 1, 0, 0, n) + A[i]
        # h = H[i]
        # a = A[i]
        # tmp = query(1, h + 1) #[1, h)での最大値
        # print (h, tmp)
        update(H[i] - 1, dp[i])
        # ans = max(ans, tmp + a)
        # print (data)

    print (query(0, N, 0, 0, n))

if __name__ == '__main__':
    main()