def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            if s!=s[::-1]:
                print(s[:ans1])
            else:
                print(s[0])

        else:
            s=s[::-1]
            s=s[:ans2]
            if s!=s[::-1]:
                print(s[:ans2])
            else:
                print(s[0])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            s=[:ans2]
            if s==s[::-1]:
                print(s[:ans2])
            else:
                print(s[0])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s[:ans2])
            else:
                print(s[0])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            s=s[:ans1]
            if s==s[::-1]:
                print(s[:ans1])
            else:
                print(s[0])

        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s[:ans2])
            else:
                print(s[0])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            print(s[:ans2])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            print(s[:ans2])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            if s==s[::-1]:
                print(s[:ans1])
            else:
                print(s[0])

        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s[:ans2])
            else:
                print(s[0])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


temp=""
def is_palindrome(a,b):
    while(a<=b):
        if temp[a]!=temp[b]:
            return 0
        a+=1
        b-=1
    return i+1
t=int(input())
for _ in range(t):
    s=input()
    n=len(s)
    ans=0
    a=0
    b=n-1
    while(a<b):
        if s[a]!=s[b]:
            break
        a+=1
        b-=1
    ans=max(ans,a+n-1-b)
    oc=ans
    p=s[a:b+1]
    toprint=""
    temp=""
    for i in range(len(p)):
        temp+=p[i]
        if oc+is_palindrome(0,i)>ans:
            ans=oc+is_palindrome(0,i)
            toprint=temp
    temp=""
    p=p[::-1]
    for i in range(len(p)):
        temp+=p[i]
        if oc+is_palindrome(0,i)>ans:
            ans=oc+is_palindrome(0,i)
            toprint=temp
    print(s[0:a]+toprint+s[0:a][::-1])


temp=""
def is_palindrome(a,b):
    while(a<=b):
        if temp[a]!=temp[b]:
            return 0
        a+=1
        b-=1
    return i+1
t=int(input())
for _ in range(t):
    s=input()
    n=len(s)
    ans=0
    a=0
    b=n-1
    while(a<b):
        if s[a]!=s[b]:
            break
        a+=1
        b-=1
    ans=max(ans,a+n-1-b)
    oc=ans
    p=s[a:b+1]
    toprint=0
    temp=""
    for i in range(len(p)):
        temp+=p[i]
        if oc+is_palindrome(0,i)>ans:
            ans=oc+is_palindrome(0,i)
            toprint=temp
    temp=""
    p=p[::-1]
    for i in range(len(p)):
        temp+=p[i]
        if oc+is_palindrome(0,i)>ans:
            ans=oc+is_palindrome(0,i)
            toprint=temp
    print(s[0:a]+toprint+s[0:a][::-1])


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

for _ in range(val()):
    s = st()
    ans = ''

    n = len(s)
    if n == 1:
        print(s)
        continue
    i,j = 0,n-1

    while i < j and s[i] == s[j]:
        i += 1
        j -= 1

    sidestring = s[:i]

    mid = ''
    for k in range(i,j + 1):
        curr = s[i:k + 1]
        if curr == curr[::-1] and len(curr) > len(mid):mid = curr

    for k in range(j,i - 1,-1):
        curr = s[k:j + 1]
        if curr == curr[::-1] and len(curr) > len(mid):mid = curr
    ans2 = sidestring + mid + sidestring[::-1]
    if len(ans2) > len(ans):ans = ans2

    print(ans)


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

for _ in range(val()):
    s = st()
    ans = ''
    if len(s) == 1:
        print(s)
        continue
    for i in range(len(s)):
        if s[:i + 1] == s[:i + 1][::-1]:ans = s[:i + 1]

    n = len(s)
    i,j = 0,n-1
    while s[i] == s[j] and i <= j:
        i += 1
        j -= 1
    sidestring = s[:i]

    mid = ''
    for k in range(i,j):
        curr = s[i:k + 1]
        if curr == curr[::-1] and len(curr) > len(mid):mid = curr

    for k in range(j,i,-1):
        curr = s[k:j + 1]
        if curr == curr[::-1] and len(curr) > len(mid):mid = curr
    ans2 = sidestring + mid + sidestring[::-1]
    if len(ans2) > len(ans):ans = ans2

    print(ans)


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

for _ in range(val()):
    s = st()
    ans = ''

    n = len(s)
    if n == 1:
        print(s)
        continue
    i,j = 0,n-1
    while i <= j and s[i] == s[j]:
        i += 1
        j -= 1
    if i - 1 == j + 1:
        i -= 1
        j += 1
    sidestring = s[:i]

    mid = ''
    for k in range(i,j):
        curr = s[i:k + 1]
        if curr == curr[::-1] and len(curr) > len(mid):mid = curr

    for k in range(j,i,-1):
        curr = s[k:j + 1]
        if curr == curr[::-1] and len(curr) > len(mid):mid = curr
    ans2 = sidestring + mid + sidestring[::-1]
    if len(ans2) > len(ans):ans = ans2

    print(ans)


from sys import stdin, gettrace
if not gettrace():
    def input():
        return next(stdin)[:-1]

def main():
    def palindrome(s,si,ei):
        if si>=ei:
            return True
        if s[si]==s[ei]:
            return palindrome(s,si+1,ei-1)
        elif s[si]!=s[ei]:
            return False

    def solve():
        s=input()
        n=len(s)
        if n==1:
            print(s)
            return
        i,j,l=0,n-1,0
        while i<j and s[i]==s[j]:
            i+=1
            j-=1
            l+=1
        if i==j or i-j==1:
            print(s)
            return
        pmaxx,smaxx=0,0
        pnote,snote=l,n-l
        for i in range(l+1,n-l-1):
            stm=palindrome(s,l,i)
            if stm and (i-l+1)>pmaxx:
                pnote=i
                pmaxx=i-l+1
        for j in range(n-l-2,l-1,-1):
            stm=palindrome(s,j,n-l-1)
            if stm and (n-l-j)>smaxx:
                snote=j
                smaxx=n-l-j
        if pmaxx==0 and smaxx==0 and l==0:
            print(s[0])
            return

        if pmaxx>=smaxx:
            final=s[0:l:]+s[l:pnote+1:]+s[n-l::]
        else:
            final=s[0:l:]+s[snote:n-l:]+s[n-l::]
        print(final)
        return

    t=int(input())
    for i in range(t):
        solve()

if __name__ == "__main__":
    main()


## tle at test case 55
def gen_lps(pattern,m):
    pre_match=0
    i=1 #in any case 0 will be there at the first index that's why i is starting from 1
    lps=[0]*m

    while i<m:
        if pattern[i]==pattern[pre_match]:
            pre_match+=1
            lps[i]=pre_match
            i+=1
        else:
            if pre_match==0:
                lps[i]=0
                i+=1
            else:
                pre_match=lps[pre_match-1]

    return lps[-1]

def largest_pre_pal(rem):
    new=rem+'#'+rem[::-1]
    m=len(new)
    lll=gen_lps(new,m)
    return lll

def solve():
    s=input()
    n=len(s)
    if n==1:
        print(s)
        return
    i,j,l=0,n-1,0
    while i<j and s[i]==s[j]:
        i+=1
        j-=1
        l+=1
    if i==j or i-j==1:
        print(s)
        return
    pre_len=largest_pre_pal(s[l:n-l-1])
    suff_len=largest_pre_pal(s[n-l-1:l:-1])

    if pre_len>=suff_len:
        final=s[0:l:]+s[l:l+pre_len:]+s[n-l::]
    else:
        final=s[0:l:]+s[n-l-suff_len:n-l:]+s[n-l::]
    print(final)

t=int(input())
for i in range(t):
    solve()


from sys import stdin, gettrace
def input():
   return stdin.buffer.readline()

def main():
    def palindrome(s,si,ei):
        if si>=ei:
            return True
        if s[si]==s[ei]:
            return palindrome(s,si+1,ei-1)
        elif s[si]!=s[ei]:
            return False

    def solve():
        s=input()
        n=len(s)
        if n==1:
            print(s)
            return
        i,j,l=0,n-1,0
        while i<j and s[i]==s[j]:
            i+=1
            j-=1
            l+=1
        if i==j or i-j==1:
            print(s)
            return
        pmaxx,smaxx=0,0
        pnote,snote=l,n-l
        for i in range(l+1,n-l-1):
            stm=palindrome(s,l,i)
            if stm and (i-l+1)>pmaxx:
                pnote=i
                pmaxx=i-l+1
        for j in range(n-l-2,l-1,-1):
            stm=palindrome(s,j,n-l-1)
            if stm and (n-l-j)>smaxx:
                snote=j
                smaxx=n-l-j
        if pmaxx==0 and smaxx==0 and l==0:
            print(s[0])
            return

        if pmaxx>=smaxx:
            final=s[0:l:]+s[l:pnote+1:]+s[n-l::]
        else:
            final=s[0:l:]+s[snote:n-l:]+s[n-l::]
        print(final)
        return

    t=int(input())
    for i in range(t):
        solve()

if __name__ == "__main__":
    main()


import sys
sys.setrecursionlimit(10000)
def palindrome(s,si,ei):
    if si>=ei:
        return True
    if s[si]==s[ei]:
        return palindrome(s,si+1,ei-1)
    elif s[si]!=s[ei]:
        return False

def solve():
    s=input()
    n=len(s)
    if n==1:
        print(s)
        return
    i,j,l=0,n-1,0
    while i<j and s[i]==s[j]:
        i+=1
        j-=1
        l+=1
    if i==j or i-j==1:
        print(s)
        return
    pmaxx,smaxx=0,0
    pnote,snote=l,n-l
    for i in range(l+1,n-l-1):
        stm=palindrome(s,l,i)
        if stm and (i-l+1)>pmaxx:
            pnote=i
            pmaxx=i-l+1
    for j in range(n-l-2,l-1,-1):
        stm=palindrome(s,j,n-l-1)
        if stm and (n-l-j)>smaxx:
            snote=j
            smaxx=n-l-j
    if pmaxx==0 and smaxx==0 and l==0:
        print(s[0])
        return

    if pmaxx>=smaxx:
        final=s[0:l:]+s[l:pnote+1:]+s[n-l::]
    else:
        final=s[0:l:]+s[snote:n-l:]+s[n-l::]
    print(final)
    return

t=int(input())
for i in range(t):
    solve()


def gen_lps(pattern,m):
    pre_match=0
    i=1 #in any case 0 will be there at the first index that's why i is starting from 1
    lps=[0]*m

    while i<m:
        if pattern[i]==pattern[pre_match]:
            pre_match+=1
            lps[i]=pre_match
            i+=1
        else:
            if pre_match==0:
                lps[i]=0
                i+=1
            else:
                pre_match=0

    return lps[-1]

def largest_pre_pal(rem):
    new=rem+'#'+rem[::-1]
    m=len(new)
    lll=gen_lps(new,m)
    return lll

def solve():
    s=input()
    n=len(s)
    if n==1:
        print(s)
        return
    i,j,l=0,n-1,0
    while i<j and s[i]==s[j]:
        i+=1
        j-=1
        l+=1
    if i==j or i-j==1:
        print(s)
        return
    pre_len=largest_pre_pal(s[l:n-l-1])
    suff_len=largest_pre_pal(s[n-l-1:l:-1])

    if pre_len>=suff_len:
        final=s[0:l:]+s[l:l+pre_len:]+s[n-l::]
    else:
        final=s[0:l:]+s[n-l-suff_len:n-l:]+s[n-l::]
    print(final)

t=int(input())
for i in range(t):
    solve()


from sys import stdin, gettrace
if not gettrace():
    def input():
        return next(stdin)

def main():
    def palindrome(s,si,ei):
        if si>=ei:
            return True
        if s[si]==s[ei]:
            return palindrome(s,si+1,ei-1)
        elif s[si]!=s[ei]:
            return False

    def solve():
        s=input()
        n=len(s)
        if n==1:
            print(s)
            return
        i,j,l=0,n-1,0
        while i<j and s[i]==s[j]:
            i+=1
            j-=1
            l+=1
        if i==j or i-j==1:
            print(s)
            return
        pmaxx,smaxx=0,0
        pnote,snote=l,n-l
        for i in range(l+1,n-l-1):
            stm=palindrome(s,l,i)
            if stm and (i-l+1)>pmaxx:
                pnote=i
                pmaxx=i-l+1
        for j in range(n-l-2,l-1,-1):
            stm=palindrome(s,j,n-l-1)
            if stm and (n-l-j)>smaxx:
                snote=j
                smaxx=n-l-j
        if pmaxx==0 and smaxx==0 and l==0:
            print(s[0])
            return

        if pmaxx>=smaxx:
            final=s[0:l:]+s[l:pnote+1:]+s[n-l::]
        else:
            final=s[0:l:]+s[snote:n-l:]+s[n-l::]
        print(final)
        return

    t=int(input())
    for i in range(t):
        solve()

if __name__ == "__main__":
    main()


import sys
sys.setrecursionlimit(1000000000)
def palindrome(s,si,ei):
    if si>=ei:
        return True
    if s[si]==s[ei]:
        return palindrome(s,si+1,ei-1)
    elif s[si]!=s[ei]:
        return False

def solve():
    s=input()
    n=len(s)
    if n==1:
        print(s)
        return
    i,j,l=0,n-1,0
    while i<j and s[i]==s[j]:
        i+=1
        j-=1
        l+=1
    if i==j or i-j==1:
        print(s)
        return
    pmaxx,smaxx=0,0
    pnote,snote=l,n-l
    for i in range(l+1,n-l-1):
        stm=palindrome(s,l,i)
        if stm and (i-l+1)>pmaxx:
            pnote=i
            pmaxx=i-l+1
    for j in range(n-l-2,l-1,-1):
        stm=palindrome(s,j,n-l-1)
        if stm and (n-l-j)>smaxx:
            snote=j
            smaxx=n-l-j
    if pmaxx==0 and smaxx==0 and l==0:
        print(s[0])
        return

    if pmaxx>=smaxx:
        final=s[0:l:]+s[l:pnote+1:]+s[n-l::]
    else:
        final=s[0:l:]+s[snote:n-l:]+s[n-l::]
    print(final)
    return

t=int(input())
for i in range(t):
    solve()


from sys import stdin, gettrace
sys.setrecursionlimit(10000000)
if not gettrace():
    def input():
        return next(stdin)[:-1]

def main():
    def palindrome(s,si,ei):
        if si>=ei:
            return True
        if s[si]==s[ei]:
            return palindrome(s,si+1,ei-1)
        elif s[si]!=s[ei]:
            return False

    def solve():
        s=input()
        n=len(s)
        if n==1:
            print(s)
            return
        i,j,l=0,n-1,0
        while i<j and s[i]==s[j]:
            i+=1
            j-=1
            l+=1
        if i==j or i-j==1:
            print(s)
            return
        pmaxx,smaxx=0,0
        pnote,snote=l,n-l
        for i in range(l+1,n-l-1):
            stm=palindrome(s,l,i)
            if stm and (i-l+1)>pmaxx:
                pnote=i
                pmaxx=i-l+1
        for j in range(n-l-2,l-1,-1):
            stm=palindrome(s,j,n-l-1)
            if stm and (n-l-j)>smaxx:
                snote=j
                smaxx=n-l-j
        if pmaxx==0 and smaxx==0 and l==0:
            print(s[0])
            return

        if pmaxx>=smaxx:
            final=s[0:l:]+s[l:pnote+1:]+s[n-l::]
        else:
            final=s[0:l:]+s[snote:n-l:]+s[n-l::]
        print(final)
        return

    t=int(input())
    for i in range(t):
        solve()

if __name__ == "__main__":
    main()


from math import *
# from sys import stdin,stdout

def binarySearch(arr,x,i):
	l=i
	r=len(arr)-1
	while l <= r:
		mid = (l + r)//2;
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def js(arr,x):
	l=0
	r=len(arr)-1
	ans=-1
	while(l<=r):
		m=(l+r)//2
		if(arr[m]<=x):
			ans=m
			l=m+1
		else:
			r=m-1
	return ans

def jg(arr,x,i):
	l=i
	r=len(arr)-1
	ans=-1
	while(l<=r):
		m=(l+r)//2
		if(arr[m]>=x):
			ans=m
			r=m-1
		else:
			l=m+1
	return ans

# def ceil(a,b):
# 	if a%b == 0:
# 		return int(a/b)
# 	else:
# 		return (a//b + 1)

for __ in range(int(input())):
	s=input()
	x=0
	y=len(s)-1
	suf=''
	pre=''
	while(x<y):
		if(s[x]==s[y]):
			suf=s[x]+suf
			pre+=s[y]
			x+=1
			y-=1
		else:
			break
	p1=''
	for i in range(x+1,y):
		if(s[x:i]==s[x:i][::-1]):
			p1=s[x:i]
	p2=''
	i=y
	while(i>x):
		if(s[i:y+1]==s[i:y+1][::-1]):
			p2=s[i:y+1]
		i-=1
	if(pre==''):
		if(len(p1)>len(p2)):
			ans=p1
		elif(len(p1)<=len(p2) and p1!=''):
			ans=p2
		else:
			ans=s[0]
		print(ans)
	else:
		ans1=pre+p1+suf
		ans2=pre+p2+suf
		if(len(ans1)>len(ans2)):
			ans=ans1
		else:
			ans=ans2

		print(ans)


from math import *
# from sys import stdin,stdout

def binarySearch(arr,x,i):
	l=i
	r=len(arr)-1
	while l <= r:
		mid = (l + r)//2;
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def js(arr,x):
	l=0
	r=len(arr)-1
	ans=-1
	while(l<=r):
		m=(l+r)//2
		if(arr[m]<=x):
			ans=m
			l=m+1
		else:
			r=m-1
	return ans

def jg(arr,x,i):
	l=i
	r=len(arr)-1
	ans=-1
	while(l<=r):
		m=(l+r)//2
		if(arr[m]>=x):
			ans=m
			r=m-1
		else:
			l=m+1
	return ans

# def ceil(a,b):
# 	if a%b == 0:
# 		return int(a/b)
# 	else:
# 		return (a//b + 1)

for __ in range(int(input())):
	s=input()
	x=0
	y=len(s)-1
	suf=''
	pre=''
	while(x<=y):
		if(s[x]==s[y]):
			if(x!=y):
				suf=s[x]+suf
				x+=1
			pre+=s[y]
			y-=1
		else:
			break
	p1=''
	for i in range(x+1,y):
		if(s[x:i]==s[x:i][::-1]):
			p1=s[x:i]
	p2=''
	i=y
	while(i>x):
		if(s[i:y+1]==s[i:y+1][::-1]):
			p2=s[i:y+1]
		i-=1
	if(pre==''):
		if(len(p1)>len(p2)):
			ans=p1
		elif(len(p1)<=len(p2) and p1!=''):
			ans=p2
		else:
			ans=s[0]
		print(ans)
	else:
		ans1=pre+p1+suf
		ans2=pre+p2+suf
		if(len(ans1)>len(ans2)):
			ans=ans1
		else:
			ans=ans2

		print(ans)


from math import *
# from sys import stdin,stdout

def binarySearch(arr,x,i):
	l=i
	r=len(arr)-1
	while l <= r:
		mid = (l + r)//2;
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def js(arr,x):
	l=0
	r=len(arr)-1
	ans=-1
	while(l<=r):
		m=(l+r)//2
		if(arr[m]<=x):
			ans=m
			l=m+1
		else:
			r=m-1
	return ans

def jg(arr,x,i):
	l=i
	r=len(arr)-1
	ans=-1
	while(l<=r):
		m=(l+r)//2
		if(arr[m]>=x):
			ans=m
			r=m-1
		else:
			l=m+1
	return ans

# def ceil(a,b):
# 	if a%b == 0:
# 		return int(a/b)
# 	else:
# 		return (a//b + 1)

for __ in range(int(input())):
	s=input()
	x=0
	y=len(s)-1
	suf=''
	pre=''
	while(x<=y):
		if(s[x]==s[y]):
			if(x!=y):
				suf=s[x]+suf
				x+=1
			pre+=s[y]
			y-=1
		else:
			break
	p1=''
	for i in range(x+1,y+1):
		if(s[x:i]==s[x:i][::-1]):
			p1=s[x:i]
	p2=''
	i=y
	while(i>x):
		if(s[i:y+1]==s[i:y+1][::-1]):
			p2=s[i:y+1]
		i-=1
	# print(pre,suf,p1,p2)
	if(pre==''):
		if(len(p1)>len(p2)):
			ans=p1
		elif(len(p1)<=len(p2) and p1!=''):
			ans=p2
		else:
			ans=s[0]
		print(ans)
	else:
		ans1=pre+p1+suf
		ans2=pre+p2+suf
		if(len(ans1)>len(ans2)):
			ans=ans1
		else:
			ans=ans2

		print(ans)


import math, collections, sys
x = ''
y = ''
def checkpal(s):
    for i in range(len(s)):
        if s[i] != s[len(s)-1-i]:
            return False
    return True
def suffix(l, s):
    test = ''
    val = ''
    for i in range(l, len(s)):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def prefix(r, s):
    test = ''
    val = ''
    for i in range(r, -1, -1):
        test+=s[i]
        if checkpal(test):
            val = test
    return val[::-1]
def getString(l, r, s):
    global x, y
    if l > r:
        return
    if l == r:
        x+=s[l]
        return
    if s[l] == s[r]:
        x+=s[l]
        y+=s[r]
        getString(l+1, r-1, s)
    else:
        p = suffix(l, s)
        q = prefix(r, s)
        if len(p) > len(q):
            x+=p
        else:
            y+=q
def solve():
    s = input()
    n = len(s)
    getString(0, n-1, s)
    print(x+y[::-1])
for _ in range(int(input())):
    x = ''
    y = ''
    solve()


import math, collections, sys
x = ''
y = ''
def checkpal(s):
    for i in range(len(s)):
        if s[i] != s[len(s)-1-i]:
            return False
    return True
def suffix(l, r, s):
    test = ''
    val = ''
    for i in range(l, r+1):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def prefix(l, r, s):
    test = ''
    val = ''
    for i in range(r, l-1, -1):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def getString(l, r, s):
    global x, y
    if l > r:
        return
    if l == r:
        x+=s[l]
        return
    if s[l] == s[r]:
        x+=s[l]
        y+=s[r]
        getString(l+1, r-1, s)
    else:
        p = suffix(l, r, s)
        q = prefix(l, r, s)
        if len(p) > len(q):
            x+=p
        else:
            y+=q
        return
def solve():
    s = input()
    n = len(s)
    getString(0, n-1, s)
    print(x+y[::-1])
for _ in range(int(input())):
    x = ''
    y = ''
    solve()


import math, collections, sys
sys.setrecursionlimit(10**5)
x = ''
y = ''
def checkpal(s):
    for i in range(len(s)):
        if s[i] != s[len(s)-1-i]:
            return False
    return True
def suffix(l, r, s):
    test = ''
    val = ''
    for i in range(l, r+1):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def prefix(l, r, s):
    test = ''
    val = ''
    for i in range(r, l-1, -1):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def getString(l, r, s):
    global x, y
    if l > r:
        return
    if l == r:
        x+=s[l]
        return
    if s[l] == s[r]:
        x+=s[l]
        y+=s[r]
        getString(l+1, r-1, s)
    else:
        p = suffix(l, r, s)
        q = prefix(l, r, s)
        if len(p) > len(q):
            x+=p
        else:
            y+=q
        return
def solve():
    s = input()
    n = len(s)
    getString(0, n-1, s)
    print(x+y[::-1])
for _ in range(int(input())):
    x = ''
    y = ''
    solve()


import math, collections, sys
x = ''
y = ''
def checkpal(s):
    for i in range(len(s)):
        if s[i] != s[len(s)-1-i]:
            return False
    return True
def suffix(l, s):
    test = ''
    val = ''
    for i in range(l, len(s)):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def prefix(r, s):
    test = ''
    val = ''
    for i in range(r, -1, -1):
        test+=s[i]
        if checkpal(test):
            val = test
    return val
def getString(l, r, s):
    global x, y
    if l > r:
        return
    if l == r:
        x+=s[l]
        return
    if s[l] == s[r]:
        x+=s[l]
        y+=s[r]
        getString(l+1, r-1, s)
    else:
        p = suffix(l, s)
        q = prefix(r, s)
        if len(p) > len(q):
            x+=p
        else:
            y+=q
def solve():
    s = input()
    n = len(s)
    getString(0, n-1, s)
    print(x+y[::-1])
for _ in range(int(input())):
    x = ''
    y = ''
    solve()


# http://codeforces.com/problemset/problem/1326/D1

import sys

t = int(sys.stdin.readline())
for _ in range(t):
    s = sys.stdin.readline().strip()

    en = 0
    for i in range(len(s) // 2):
        if s[i] == s[-(i+1)]:
            en += 2
        else:
            break

    if en != len(s):
        bn = 1
        bi = en//2
        for i in range(en//2, len(s)-1-en//2):
            pn = 2*min(i-en//2, len(s)-1-en//2-i) + 1
            if pn <= bn:
                continue
            for j in range(pn//2+1):
                if s[i-j] != s[i+j]:
                    break
            else:
                bn = pn
                bi = i
        for i in range(en//2, len(s)-1-en//2):
            pn = 2*min(i-en//2+1, len(s)-1-en//2-i)
            if pn <= bn:
                continue
            for j in range(pn//2):
                if s[i-j] != s[i+j+1]:
                    break
            else:
                bn = pn
                bi = i
    else:
        bn = 0
        bi = 1

    ss = s[:en//2] + s[bi-(bn-1)//2:bi+bn//2+1] + s[len(s)-en//2:]
    print(ss)


# http://codeforces.com/problemset/problem/1326/D1

import sys

t = int(sys.stdin.readline())
for _ in range(t):
    s = sys.stdin.readline().strip()

    en = 0
    for i in range(len(s) // 2):
        if s[i] == s[-(i+1)]:
            en += 2
        else:
            break

    bn = 1
    bi = en // 2
    for i in range(en//2+1, len(s)-1-en//2):
        pn = 2*min(i-en//2, len(s)-1-en//2-i) + 1
        if pn <= bn:
            continue
        for j in range(pn//2+1):
            if s[i-j] != s[i+j]:
                break
        else:
            bn = pn
            bi = i
    for i in range(en//2, len(s)-1-en//2):
        pn = 2*min(i-en//2+1, len(s)-1-en//2-i)
        if pn <= bn:
            continue
        for j in range(pn//2):
            if s[i-j] != s[i+j+1]:
                break
        else:
            bn = pn
            bi = i

    ss = s[:en//2] + s[bi-(bn-1)//2:bi+bn//2+1] + s[len(s)-en//2:]
    print(ss)


# http://codeforces.com/problemset/problem/1326/D1

import sys

t = int(sys.stdin.readline())
for _ in range(t):
    s = sys.stdin.readline().strip()

    en = 0
    for i in range(len(s) // 2):
        if s[i] == s[-(i+1)]:
            en += 2
        else:
            break

    bn = 0
    bi = en//2
    for i in range(en//2, len(s)-1-en//2):
        pn = 2*min(i-en//2, len(s)-1-en//2-i) + 1
        if pn <= bn:
            continue
        for j in range(pn//2+1):
            if s[i-j] != s[i+j]:
                break
        else:
            bn = pn
            bi = i
    for i in range(en//2, len(s)-1-en//2):
        pn = 2*min(i-en//2+1, len(s)-1-en//2-i)
        if pn <= bn:
            continue
        for j in range(pn//2):
            if s[i-j] != s[i+j+1]:
                break
        else:
            bn = pn
            bi = i

    ss = s[:en//2] + s[bi-(bn-1)//2:bi+bn//2+1] + s[len(s)-en//2:]
    print(ss)


for _ in range(int(input())):
    s = input()
    n = len(s)
    ans=''
    for i in range(n):
        for j in range(n-1,i-1,-1):
            k = s[:i]+s[j:]
#            print(s[:i],'k',s[j:],k,j,i)
            if k==k[::-1] and len(ans)<len(k):
                ans=k
    print(ans)


for _ in range(int(input())):
    s = input()
    n = len(s)
    le=0
    ans=''
    for i in range(n):
        if s[i]!=s[n-1-i]:
            break
        if i>=n-1-i:
            break
        le=i+1
#    print(le)
    ans=s[:le]+s[n-le:]
    for i in range(le,n-le):
        k = s[:i+1]+s[n-le:]
#        print(k,s[:i+1],s[n-le:])
        if k==k[::-1] and len(k)>len(ans):
            ans=k
    for i in range(n-le-1,le,-1):
        k = s[:le]+s[i:]
#        print(k)
        if k==k[::-1] and len(k)>len(ans):
            ans=k
    print(ans)


for _ in range(int(input())):
    s = input()
    n = len(s)
    le=0
    ans=''
    for i in range(n):
        if s[i]!=s[n-1-i]:
            break
        if i>=n-1-i:
            break
        le=i+1
#    print(le)
    for i in range(le,n-le):
        k = s[:i+1]+s[n-le:]
#        print(k,s[:i+1],s[n-le:])
        if k==k[::-1] and len(k)>len(ans):
            ans=k
    for i in range(n-1-le,le,-1):
        k = s[:le]+s[i:]
#        print(k)
        if k==k[::-1] and len(k)>len(ans):
            ans=k
    print(ans)


for _ in range(int(input())):
    s = input()
    n = len(s)
    ans=''
    for i in range(n):
        for j in range(n,i-1,-1):
            k = s[:i]+s[j:]
#            print(k)
            if k==k[::-1] and len(ans)<len(k):
                ans=k
    print(ans)


for _ in range(int(input())):
    s = input()
    n = len(s)
    ans=''
    le=0
    for i in range(n):
        for j in range(n,i-1,-1):
            k = s[:i]+s[j:]
            if k==k[::-1] and le<(i+n-j):
                ans=k
                le = i+(n-j)
    print(ans)


def longest_palindrome(s1):
    left_part = ''
    right_part = ''
    s2 = s1
    left = 0
    right = -1
    flag = 0
    while left + abs(right) <= len(s):
        # print('left =', left, 'right =', right, 'left_part =', left_part, 'right_part =', right_part)
        if flag == 0:
            if s2[left] == s2[right]:
                left += 1
                right -= 1
            else:
                left_part += s2[:left]
                if right != -1:
                    right_part += s2[right + 1:]
                flag = 1
        else:
            if s2[left] != s2[right]:
                right -= 1
            else:
                start_left = left
                start_right = right
                while left + abs(right) <= len(s):
                    # print(left, right)
                    if s2[left] == s2[right]:
                        left += 1
                        right -= 1
                    else:
                        break
                if left + abs(right) > len(s):
                    # print('Here', start_left, start_right - 1, s2[start_left:start_right + 1])
                    left_part += s2[start_left:start_right + 1] + right_part
                    break
                else:
                    left = start_left

    return left_part

for _ in range(int(input())):
    s = input()
    if s == s[::-1]:
        print(s)
    else:
        s2 = longest_palindrome(s)
        s3 = longest_palindrome(s[::-1])

        print(s2 if len(s2) > len(s3) else s3)


def longest_palindrome(s1):
    left_part = ''
    right_part = ''
    s2 = s1
    left = 0
    right = -1
    flag = 0
    while left + abs(right) <= len(s):
        # print('left =', left, 'right =', right, 'left_part =', left_part, 'right_part =', right_part)
        if flag == 0:
            if s2[left] == s2[right]:
                left += 1
                right -= 1
            else:
                left_part += s2[:left]
                if right != -1:
                    right_part += s2[right + 1:]
                flag = 1
        else:
            if s2[left] != s2[right]:
                right -= 1
            else:
                start_left = left
                start_right = right
                while left + abs(right) <= len(s):
                    # print(left, right)
                    if s2[left] == s2[right]:
                        left += 1
                        right -= 1
                    else:
                        break
                if left + abs(right) > len(s):
                    # print('Here', start_left, start_right - 1, s2[start_left:start_right + 1])
                    left_part += s2[start_left:start_right + 1] + right_part
                    break
                else:
                    left = start_left
                    right = start_right - 1
                # print('left =', left)

    return left_part

for _ in range(int(input())):
    s = input()
    if s == s[::-1]:
        print(s)
    else:
        s2 = longest_palindrome(s)
        # print(s[::-1])
        s3 = longest_palindrome(s[::-1])
        # print(s2, s3)

        print(s2 if len(s2) > len(s3) else s3)


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

import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 998244353

for _ in range(INT()):
    S = input()
    N = len(S)
    L = []
    i = 0
    j = N - 1
    while i < j:
        if S[i] == S[j]:
            L.append(S[i])
            i += 1
            j -= 1
        else:
            break
    R = L[::-1]
    if i == j:
        L.append(S[i])
    k = j
    mx = 0
    L2 = []
    while i < k:
        tmp = []
        i2 = i
        k2 = k
        while i2 < k2:
            if S[i2] == S[k2]:
                tmp.append(S[i2])
                i2 += 1
                k2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if i2 == k2:
                tmp.append(S[i2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                L2 = tmp
        k -= 1
    if not L2:
        L2.append(S[i])
    k = i
    mx = 0
    R2 = []
    while k < j:
        tmp = []
        k2 = k
        j2 = j
        while k2 < j2:
            if S[k2] == S[j2]:
                tmp.append(S[k2])
                k2 += 1
                j2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if k2 == j2:
                tmp.append(S[j2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                R2 = tmp
        k += 1
    if not R2:
        R2.append(S[j])
    if len(L2) > len(R2):
        ans = L + L2 + R
    else:
        ans = L + R2 + R
    if not ans:
        ans = S[0]
    print(''.join(ans))


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

import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 998244353

for _ in range(INT()):
    S = input()
    N = len(S)
    L = []
    i = 0
    j = N - 1
    while i < j:
        if S[i] == S[j]:
            L.append(S[i])
            i += 1
            j -= 1
        else:
            break
    else:
        print(S)
        continue
    R = L[::-1]
    k = j
    mx = 0
    L2 = []
    while i < k:
        tmp = []
        i2 = i
        k2 = k
        while i2 < k2:
            if S[i2] == S[k2]:
                tmp.append(S[i2])
                i2 += 1
                k2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if i2 == k2:
                tmp.append(S[i2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                L2 = tmp
        k -= 1
    if not L2:
        L2.append(S[i])
    k = i
    mx = 0
    R2 = []
    while k < j:
        tmp = []
        k2 = k
        j2 = j
        while k2 < j2:
            if S[k2] == S[j2]:
                tmp.append(S[k2])
                k2 += 1
                j2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if k2 == j2:
                tmp.append(S[j2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                R2 = tmp
        k += 1
    if not R2:
        R2.append(S[j])
    if len(L2) > len(R2):
        ans = L + L2 + R
    else:
        ans = L + R2 + R
    print(''.join(ans))


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

import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 998244353

for _ in range(INT()):
    S = input()
    N = len(S)
    L = []
    i = 0
    j = N - 1
    while i < j:
        if S[i] == S[j]:
            L.append(S[i])
            i += 1
            j -= 1
        else:
            break
    R = L[::-1]
    k = j
    mx = 0
    L2 = []
    while i < k:
        tmp = []
        i2 = i
        k2 = k
        while i2 < k2:
            if S[i2] == S[k2]:
                tmp.append(S[i2])
                i2 += 1
                k2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if i2 == k2:
                tmp.append(S[i2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                L2 = tmp
        k -= 1
    if not L2:
        L2.append(S[i])
    k = i
    mx = 0
    R2 = []
    while k < j:
        tmp = []
        k2 = k
        j2 = j
        while k2 < j2:
            if S[k2] == S[j2]:
                tmp.append(S[k2])
                k2 += 1
                j2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if k2 == j2:
                tmp.append(S[j2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                R2 = tmp
        k += 1
    if not R2:
        R2.append(S[j])
    if len(L2) > len(R2):
        ans = L + L2 + R
    else:
        ans = L + R2 + R
    print(''.join(ans))


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

import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 998244353

for _ in range(INT()):
    S = input()
    N = len(S)
    L = []
    i = 0
    j = N - 1
    while i < j:
        if S[i] == S[j]:
            L.append(S[i])
            i += 1
            j -= 1
        else:
            break
    R = L[::-1]
    if i == j:
        L.append(S[i])
    k = j
    mx = 0
    L2 = []
    while i < k:
        tmp = []
        i2 = i
        k2 = k
        while i2 < k2:
            if S[i2] == S[k2]:
                tmp.append(S[i2])
                i2 += 1
                k2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if i2 == k2:
                tmp.append(S[i2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                L2 = tmp
        k -= 1
    k = i
    mx = 0
    R2 = []
    while k < j:
        tmp = []
        k2 = k
        j2 = j
        while k2 < j2:
            if S[k2] == S[j2]:
                tmp.append(S[k2])
                k2 += 1
                j2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if k2 == j2:
                tmp.append(S[j2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                R2 = tmp
        k += 1
    if len(L2) > len(R2):
        ans = L + L2 + R
    else:
        ans = L + R2 + R
    if not ans:
        ans = S[0]
    print(''.join(ans))


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

import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 998244353

for _ in range(INT()):
    S = input()
    N = len(S)
    L = []
    i = 0
    j = N - 1
    while i < j:
        if S[i] == S[j]:
            L.append(S[i])
            i += 1
            j -= 1
        else:
            break
    R = L[::-1]
    k = j
    mx = 0
    L2 = []
    while i < k:
        tmp = []
        i2 = i
        k2 = k
        while i2 < k2:
            if S[i2] == S[k2]:
                tmp.append(S[i2])
                i2 += 1
                k2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if i2 == k2:
                tmp.append(S[i2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                L2 = tmp
        k -= 1
    if not L2:
        L2.append(S[i])
    k = i
    mx = 0
    R2 = []
    while k < j:
        tmp = []
        k2 = k
        j2 = j
        while k2 < j2:
            if S[k2] == S[j2]:
                tmp.append(S[k2])
                k2 += 1
                j2 -= 1
            else:
                break
        else:
            tmp2 = tmp[::-1]
            if k2 == j2:
                tmp.append(S[j2])
            tmp += tmp2
            if len(tmp) > mx:
                mx = len(tmp)
                R2 = tmp
        k += 1
    if not R2:
        R2.append(S[j])
    if len(L2) > len(R2):
        ans = L + L2 + R
    else:
        ans = L + R2 + R
    if not ans:
        ans = S[0]
    print(''.join(ans))


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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

class SuffixArray:

    class SparseTable:

        def __init__(self, A, func):
            self.N = len(A)
            self.func = func
            h = 0
            while 1<<h < self.N:
                h += 1
            self.dat = list2d(h, 1<<h, 0)
            self.height = [0] * (self.N+1)

            for i in range(2, self.N+1):
                self.height[i] = self.height[i>>1] + 1
            for i in range(self.N):
                self.dat[0][i] = A[i]
            for i in range(1, h):
                for j in range(self.N):
                    self.dat[i][j] = self.func(self.dat[i-1][j], self.dat[i-1][min(j+(1<<(i-1)), self.N-1)])

        def get(self, l, r):

            if l >= r:
                raise Exception
            a = self.height[r-l]
            return self.func(self.dat[a][l], self.dat[a][r-(1<<a)])

    def __init__(self, S):
        self.k = 1
        self.S = S
        self.N = len(S)
        self.rank = [0] * (self.N+1)
        self.tmp = [0] * (self.N+1)
        self.sa = [0] * (self.N+1)
        self.build_sa()

    def compare_sa(self, i, j):

        if self.rank[i] == self.rank[j]: res1 =  0
        elif self.rank[i] < self.rank[j]: res1 =  -1
        else: res1 = 1
        ri = self.rank[i+self.k] if i + self.k <= self.N else -1
        rj = self.rank[j+self.k] if j + self.k <= self.N else -1
        if ri == rj: res2 = 0
        elif ri < rj: res2 = -1
        else: res2 = 1
        return res1 or res2

    def build_sa(self):
        from functools import cmp_to_key

        for i in range(self.N+1):
            self.sa[i] = i
            self.rank[i] = ord(self.S[i]) if i < self.N else -1

        k = 1
        while k <= self.N:
            self.k = k
            self.sa = sorted(self.sa, key=cmp_to_key(self.compare_sa))
            k *= 2

            self.tmp[self.sa[0]] = 0
            for i in range(1, self.N+1):
                self.tmp[self.sa[i]] = self.tmp[self.sa[i-1]] + (1 if self.compare_sa(self.sa[i-1], self.sa[i]) else 0)
            for i in range(self.N+1):
                self.rank[i] = self.tmp[i]

    def build_lcp(self):

        self.lcp = [0] * (self.N+1)
        self.rsa = [0] * (self.N+1)
        for i in range(self.N+1):
            self.rsa[self.sa[i]] = i
        h = 0
        self.lcp[0] = 0
        for i in range(self.N):
            j = self.sa[self.rsa[i]-1]

            if h > 0:
                h -= 1
            while j+h < self.N and i+h < self.N:
                if self.S[j+h] != self.S[i+h]:
                    break
                h += 1
            self.lcp[self.rsa[i]-1] = h

    def build_st(self):

        self.st = self.SparseTable(self.lcp, min)

    def getLCP(self, i, j):

        return self.st.get(min(self.rsa[i], self.rsa[j]), max(self.rsa[i], self.rsa[j]))

for _ in range(INT()):
    S = input()
    N = len(S)
    i = 0
    j = N - 1
    T1 = []
    while i < j:
        if S[i] == S[j]:
            T1.append(S[i])
            i += 1
            j -= 1
        else:
            break
    else:
        print(S)
        continue
    T3 = T1[::-1]

    M = j - i + 1
    S2 = S[i:j+1] + '*' + S[i:j+1][::-1]
    N2 = len(S2)
    sa = SuffixArray(S2)
    sa.build_lcp()
    mx = a = b = 0
    for k in range(N2):
        if (sa.sa[k] < M) ^ (sa.sa[k+1] < M):
            if sa.lcp[k] > mx and (sa.sa[k] in [0, M+1] or sa.sa[k] + sa.lcp[k] in [M, N2]):
                mx = sa.lcp[k]
                a, b = sa.sa[k], sa.sa[k] + sa.lcp[k]
    T2 = list(S2[a:b])
    ans = T1 + T2 + T3
    print(''.join(ans))


def pre(s):
	p = s + '#' + s[::-1]
	pi = [0] * len(p)
	j = 0
	for i in range(1, len(p)):
		while j != 0 and p[j] != p[i]:
			j = pi[j - 1]
		if p[j] == p[i]:
			j += 1
		pi[i] = j
	return s[:j]

t = int(input())
for i in range(t):
	s = input()

	l = 0
	while l < len(s) // 2 and s[l] == s[-(l + 1)]:
		l += 1

	pp = pre(s[l:len(s)-l])
	sp = pre(s[l:len(s)-l][::-1])
	pp = pp if len(pp) > len(sp) else sp

	print(s[:l] + pp + s[len(s)-l:])


def zarray(s):
    arr=[0]*len(s)
    left,right=0,0
    for k in range(1,len(s)):
        if k>right:
            left,right=k,k
            while(right<len(s) and s[right]==s[right-left]):
                right+=1
            arr[k]=right-left
            right-=1
        else:
            k1=k-left
            if arr[k1]<right-k+1:
                arr[k]=arr[k1]
            else:
                left=k
                while (right<len(s) and s[right]==s[right-left]):
                    right+=1
                arr[k]=right-left
                right-=1
    return arr

def solve(s):
    cp1=s+'#'+s[::-1]
    cp2=s[::-1]+'#'+s
    cpy1=zarray(cp1)
    cpy2=zarray(cp2)
    maxx1=max(cpy1)
    maxx2=max(cpy2)
    if maxx1>maxx2:
        k=cpy1.index(maxx1)
        return cp1[k:k+maxx1]
    else:
        k=cpy2.index(maxx2)
        return cp2[k:k+maxx2]

def calc(s):
    i=0
    n=len(s)-1
    if len(s)==1:
        return s
    pre,suf,mid="","",""
    while (i<len(s)):
        if s[i]==s[n-i]:
            i+=1
        else:
            break
    if i>0:
        pre+=s[:i]
        suf+=pre[::-1]
        mid=solve(s[i:n-i+1])
    else:
        mid=solve(s)
    return (pre+mid+suf)

for _ in range(int(input())):
    s=input()
    print(calc(s))


def zarray(s):
    arr=[0]*len(s)
    left,right=0,0
    for k in range(1,len(s)):
        if k>right:
            left,right=k,k
            while(right<len(s) and s[right]==s[right-left]):
                right+=1
            arr[k]=right-left
            right-=1
        else:
            k1=k-left
            if arr[k1]<right-k+1:
                arr[k]=arr[k1]
            else:
                left=k
                while (right<len(s) and s[right]==s[right-left]):
                    right+=1
                arr[k]=right-left
                right-=1
    return arr

def solve(s):
    cp1=s+'#'+s[::-1]
    cp2=s[::-1]+'#'+s
    cpy1=zarray(cp1)
    cpy2=zarray(cp2)
    maxx1=max(cpy1)
    maxx2=max(cpy2)
    if maxx1>=maxx2:
        k=cpy1.index(maxx1)
        return cp1[k:k+maxx1]
    else:
        k=cpy2.index(maxx2)
        return cp2[k:k+maxx2]

def calc(s):
    i=0
    pre,suf,mid="","",""
    while (i<len(s)-i-1):
        if s[i]!=s[len(s)-i-1]:
            break
        else:
            i+=1
    if i>0:
        print(s[:i],end="")
    if len(s)>2*i:
        mid=solve(s[i:len(s)-i])
        print(mid,end="")
    if i>0:
        print(s[len(s)-i:],end="")

for _ in range(int(input())):
    s=input()
    calc(s)
    print("")


def zarray(s):
    arr=[0]*len(s)
    left,right=0,0
    for k in range(1,len(s)):
        if k>right:
            left,right=k,k
            while(right<len(s) and s[right]==s[right-left]):
                right+=1
            arr[k]=right-left
            right-=1
        else:
            k1=k-left
            if arr[k1]<right-k+1:
                arr[k]=arr[k1]
            else:
                left=k
                while (right<len(s) and s[right]==s[right-left]):
                    right+=1
                arr[k]=right-left
                right-=1
    return arr

def solve(s):
    cp1=s+'#'+s[::-1]
    cp2=s[::-1]+'#'+s
    cpy1=zarray(cp1)
    cpy2=zarray(cp2)
    maxx1=max(cpy1)
    maxx2=max(cpy2)
    if maxx1>maxx2:
        k=cpy1.index(maxx1)
        return cp1[k:k+maxx1]
    else:
        k=cpy2.index(maxx2)
        return cp2[k:k+maxx2]

def calc(s):
    i=0
    n=len(s)-1
    if len(s)==1 or s==s[::-1]:
        return s
    pre,suf,mid="","",""
    while (i<len(s)):
        if s[i]==s[n-i]:
            i+=1
        else:
            break
    if i>0:
        pre+=s[:i]
        suf+=pre[::-1]
        mid=solve(s[i:n-i+1])
    else:
        mid=solve(s)
    return (pre+mid+suf)

for _ in range(int(input())):
    s=input()
    print(calc(s))


def zarray(s):
    arr=[0]*len(s)
    left,right=0,0
    for k in range(1,len(s)):
        if k>right:
            left,right=k,k
            while(right<len(s) and s[right]==s[right-left]):
                right+=1
            arr[k]=right-left
            right-=1
        else:
            k1=k-left
            if arr[k1]<right-k+1:
                arr[k]=arr[k1]
            else:
                left=k
                while (right<len(s) and s[right]==s[right-left]):
                    right+=1
                arr[k]=right-left
                right-=1
    return arr

def solve(s):
    cp1=s+'#'+s[::-1]
    cp2=s[::-1]+'#'+s
    cpy1=zarray(cp1)
    cpy2=zarray(cp2)
    maxx1=max(cpy1)
    maxx2=max(cpy2)
    if maxx1>=maxx2:
        k=cpy1.index(maxx1)
        return cp1[k:k+maxx1]
    else:
        k=cpy2.index(maxx2)
        return cp2[k:k+maxx2]

def calc(s):
    i=0
    n=len(s)-1
    if len(s)==1 or s==s[::-1]:
        return s
    pre,suf,mid="","",""
    while (i<len(s)):
        if s[i]==s[n-i]:
            i+=1
        else:
            break
    if i>0:
        pre+=s[:i]
        suf+=pre[::-1]
        mid=solve(s[i:n-i+1])
    else:
        mid=solve(s)
    return (pre+mid+suf)

for _ in range(int(input())):
    s=input()
    print(calc(s))


for _ in range(int(input())):
    s =input()
    n = len(s)
    ans = ""
    if(s[0]==s[n-1]):
        ans+=s[0]
        i = 1
        j = n-2
        while(j>i and s[j]==s[i]):
            ans += s[i]
            i+=1
            j-=1
        extra = ""
        extra1 = ""
        if(j!=i):
            for k in range(i+1,j+1):
                if(s[i:k+1]==s[i:k+1][::-1]):
                    extra = s[i:k+1]

            k = j-1
            while(k>=i):
                if(s[k:j+1]==s[k:j+1][::-1]):
                    extra1 = s[k:j+1]
                k-=1
            if(len(extra)<len(extra1)):
                extra = extra1
       # print(i,j)
        temp = len(ans)
        ans+=extra
        if(ans!=s):
            ans+=ans[:temp][::-1]
    for i in range(n):
        if(s[:i+1]==s[:i+1][::-1] and len(ans)<len(s[:i+1])):
            ans = s[:i+1]
    for i in range(n):
        if(s[i:]==s[i:][::-1] and len(ans)<len(s[i:])):
            ans = s[i:]
    print(ans)


for _ in range(int(input())):
    s =input()
    n = len(s)
    ans = ""
    if(s[0]==s[n-1]):
        ans+=s[0]
        i = 1
        j = n-2
        while(j>i and s[j]==s[i]):
            ans += s[i]
            i+=1
            j-=1
        extra = ""
        extra1 = ""
        if(j!=i):
            for k in range(i,j+1):
                if(s[i:k+1]==s[i:k+1][::-1]):
                    extra = s[i:k+1]

            k = j
            while(k>=i):
                if(s[k:j+1]==s[k:j+1][::-1]):
                    extra1 = s[k:j+1]
                k-=1
            if(len(extra)<len(extra1)):
                extra = extra1
       # print(i,j)
        temp = len(ans)
        ans+=extra
        if(ans!=s):
            ans+=ans[:temp][::-1]
    for i in range(n):
        if(s[:i+1]==s[:i+1][::-1] and len(ans)<len(s[:i+1])):
            ans = s[:i+1]
    for i in range(n):
        if(s[i:]==s[i:][::-1] and len(ans)<len(s[i:])):
            ans = s[i:]
    print(ans)


def helper():
    xx = list(map(float, input().split()))
    le, ri, a = [], [], xx[0]
    for b in xx:
        if a > b:
            a = b
        le.append(a)
    for a in reversed(xx):
        if b > a:
            b = a
        ri.append(b)
    ri.reverse()
    return xx, le, ri

n, res = int(input()), 9e9
ss, sLe, sRi = helper()
cc, cLe, cRi = helper()
for j in sorted(range(1, n - 1), key=cc.__getitem__):
    s, c = ss[j], cc[j]
    if cLe[j - 1] + c + cRi[j + 1] < res and sLe[j - 1] < s < sRi[j + 1]:
        a = b = 9e9
        for i in range(j):
            if ss[i] < s and a > cc[i]:
                a = cc[i]
        for k in range(j + 1, n):
            if s < ss[k] and b > cc[k]:
                b = cc[k]
        if res > a + b + c:
            res = a + b + c
print(int(res) if res < 9e9 else -1)


from bisect import bisect

def main():
    n, inf, res = int(input()), 9e9, []
    ss = list(map(float, input().split()))
    cc = list(map(float, input().split()))
    srt = sorted(set(ss))
    d = {s: inf for s in srt}
    for s, c in zip(ss, cc):
        res.append(d[s] + c)
        for i in range(bisect(srt, s), len(srt)):
            t = srt[i]
            if d[t] > c:
                d[t] = c
            else:
                break
    d = {c: inf for c in srt}
    list(map(list.reverse, (ss, cc, res)))
    for i, s, c in zip(range(n), ss, cc):
        res[i] += d[s]
        for i in range(bisect(srt, s) - 2, -1, -1):
            t = srt[i]
            if d[t] > c:
                d[t] = c
            else:
                break
    r = min(res)
    print(int(r) if r < inf else -1)

if __name__ == '__main__':
    main()


from operator import __gt__, __lt__

def helper(op):
    xx = list(map(float, input().split()))
    le, ri, a = [], [], xx[0]
    for b in xx:
        if a > b:
            a = b
        le.append(a)
    for a in reversed(xx):
        if op(b, a):
            b = a
        ri.append(b)
    ri.reverse()
    return xx, le, ri

n, res = int(input()), 9e9
ss, sLe, sRi = helper(__lt__)
cc, cLe, cRi = helper(__gt__)
for j in sorted(range(1, n - 1), key=cc.__getitem__):
    s, c = ss[j], cc[j]
    if cLe[j - 1] + c + cRi[j + 1] < res and sLe[j - 1] < s < sRi[j + 1]:
        a = b = 9e9
        for i in range(j):
            if ss[i] < s and a > cc[i]:
                a = cc[i]
        for k in range(j + 1, n):
            if s < ss[k] and b > cc[k]:
                b = cc[k]
        if res > a + b + c:
            res = a + b + c
print(int(res) if res < 9e9 else -1)


#include <stdio.h>
#include <limits.h>
int main()
{
    int i,j,n;
    scanf("%d",&n);
    int a[n],s[n];
    for(i=0;i<n;i++)
    	scanf("%d",&a[i]);
    for(i=0;i<n;i++)
    	scanf("%d",&s[i]);
    int ans=INT_MAX;
    for(i=1;i<n-1;i++)
    {
        int ll=INT_MAX,lr=INT_MAX;
        for(j=i+1;j<n;j++)
        {
             if(a[i]<a[j] && s[j]<lr)
             	lr=s[j];
        }
        if(lr==INT_MAX)
        	continue;
        for(j=0;j<i;j++)
        {
            if(a[j]<a[i] && s[j]<ll)
            	ll=s[j];
        }
        if(ll==INT_MAX)
        	continue;
        int cost=ll+lr+s[i];
        if(cost<ans)
        	ans=cost;
    }
    if(ans==INT_MAX)
    	ans=-1;
    printf("%d\n",ans);
    return 0;
}


#include <stdio.h>
#include <limits.h>
int S[3000], C[3000], dp_1[3000], dp_2[3000], ans=INT_MAX;
int main(n){
    scanf("%i", &n);
    for(int i=0 ; i<n ; i++) scanf("%i", &S[i]);
    for(int i=0 ; i<n ; i++) scanf("%i", &C[i]);
    for(int i=0 ; i<n ; i++){int min=INT_MAX;
        for(int j=0 ; j<i ; j++)
            if(S[j]<S[i] && C[j]<min) min=C[j];
        dp_1[i]=min==INT_MAX?min:min+C[i];
    }
    for(int i=0 ; i<n ; i++){int min=INT_MAX;
        for(int j=0 ; j<i ; j++)
            if(S[j]<S[i] && dp_1[j]<min) min=dp_1[j];
        dp_2[i]=min==INT_MAX?min:min+C[i];
        if(dp_2[i]<ans) ans=dp_2[i];
    }
    printf("%i\n", ans==INT_MAX?-1:ans);
}


#include <stdio.h>

#define NMAX 3000
#define INF 100000000

int min(int a, int b) { return a < b ? a : b; }

void ReadVector(int vec[], int size)
{
    int i;
    for (i = 0; i < size; ++i) {
        scanf("%d", &vec[i]);
    }
}

int main()
{
    int n;
    scanf("%d", &n);

    int fonts[NMAX];
    ReadVector(fonts, n);

    int costs[NMAX];
    ReadVector(costs, n);

    int best_ends[NMAX];
    int i, j;

    for (i = 0; i < n; ++i) {
        best_ends[i] = INF;
        for (j = i + 1; j < n; ++j) {
            if (fonts[j] > fonts[i]) {
                best_ends[i] = min(best_ends[i], costs[j]);
            }
        }
    }

    int res = INF;
    for (i = 0; i < n; ++i) {
        for (j = i + 1; j < n; ++j) {
            if (fonts[j] > fonts[i]) {
                int cost = costs[i] + costs[j] + best_ends[j];
                res = min(res, cost);
            }
        }
    }

    printf("%d\n", (res < INF ? res : -1));
    return 0;
}


#include <stdio.h>

#define NMAX 3000
#define INF 1000000007

typedef long long int int64;

int min(int a, int b) { return a < b ? a : b; }

void ReadVector(int64 vec[], int size)
{
    int i;
    for (i = 0; i < size; ++i) {
        scanf("%I64d", &vec[i]);
    }
}

int main()
{
    int n;
    scanf("%d", &n);

    int64 fonts[NMAX];
    ReadVector(fonts, n);

    int64 costs[NMAX];
    ReadVector(costs, n);

    int64 best_ends[NMAX];
    int i, j;

    for (i = 0; i < n; ++i) {
        best_ends[i] = INF;
        for (j = i + 1; j < n; ++j) {
            if (fonts[j] > fonts[i]) {
                best_ends[i] = min(best_ends[i], costs[j]);
            }
        }
    }

    int64 res = INF;
    for (i = 0; i < n; ++i) {
        for (j = i + 1; j < n; ++j) {
            if (fonts[j] > fonts[i]) {
                int cost = costs[i] + costs[j] + best_ends[j];
                res = min(res, cost);
            }
        }
    }

    printf("%I64d\n", (res < INF ? res : -1));
    return 0;
}


#include <stdio.h>
int min(int a,int b){
	if(a <= 0) return b;
	return a < b ? a : b;
}
int main(void) {
	int cost[3005];
	int size[3005];
	int n,t,i,j;
	scanf("%d",&n);
	for(i=0;i<n;++i) scanf("%d",&size[i]);
	for(i=0;i<n;++i) scanf("%d",&cost[i]);
	int dp[3005] = {0};

	for(i=n-1;i>=0;--i){
		dp[i] = 1000000000;
		for(j=i+1;j<n;++j){
			if(size[i] < size[j]){
				dp[i] = min(dp[i],cost[i] + cost[j]);
			}
		}
	}

	int min_val = -1;
	for(i=0;i<n;++i){
		for(j=i+1;j<n;++j){
			if(size[i] < size[j]){
				min_val = min(min_val,cost[i] + dp[j]);
			}
		}
	}

	//for(i=0;i<n;++i) printf("%d %d\n",size[i],dp[i]);

	if(min_val > 1000000000){
		printf("-1");
	}else{
		printf("%d",min_val);
	}

	return 0;
}


#include "stdio.h"

int main()
{
    int n;
    long int minSum = 0;

    scanf("%d", &n);

    int s[n], c[n];

    for (int i = 0; i < n; ++i) {
        scanf("%d", s + i);
    }
    for (int i = 0; i < n; ++i) {
        scanf("%d", c + i);
    }

    for (int i = 0; i < n - 2; ++i) {
        for (int j = i + 1; j < n - 1; ++j) {
            for (int k = j + 1; k < n; ++k) {
                if (s[k] > s[j] && s[j] > s[i]) {
                    long int sum = c[i] + c[j] + c[k];
                    if (minSum == 0 || sum < minSum) {
                        minSum = sum;
                    }
                }
            }
        }
    }

    printf("%d", minSum);

    return 0;
}


#include "stdio.h"

int main()
{
    int n;
    long int minSum = 0;

    scanf("%d", &n);

    int s[n], c[n];

    for (int i = 0; i < n; ++i) {
        scanf("%d", s + i);
    }
    for (int i = 0; i < n; ++i) {
        scanf("%d", c + i);
    }

    for (int j = 1; j < n - 1; ++j) {
        int minI = 0, minK = 0;
        for (int i = 0; i < j; ++i) {
            if ((s[i] < s[j]) && (minI == 0 || c[i] < minI)) {
                minI = c[i];
            }
        }
        for (int k = j + 1; k < n; ++k) {
            if ((s[k] > s[j]) && (minK == 0 || c[k] < minK)) {
                minK = c[k];
            }
        }
        int sum = minI + c[j] + minK;
        if ((minI * minK != 0) && (minSum == 0 || sum < minSum)) {
            minSum = sum;
        }
    }

    if (minSum == 0) {
        printf("-1");
    } else {
        printf("%d", minSum);
    }

    return 0;
}


#include "stdio.h"

int main()
{
    int n;
    long int minSum = 0;

    scanf("%d", &n);

    int s[n], c[n];

    for (int i = 0; i < n; ++i) {
        scanf("%d", s + i);
    }
    for (int i = 0; i < n; ++i) {
        scanf("%d", c + i);
    }

    for (int i = 0; i < n - 2; ++i) {
        for (int j = i + 1; j < n - 1; ++j) {
            for (int k = j + 1; k < n; ++k) {
                if (s[k] > s[j] && s[j] > s[i]) {
                    long int sum = c[i] + c[j] + c[k];
                    if (minSum == 0 || sum < minSum) {
                        minSum = sum;
                    }
                }
            }
        }
    }

    if (minSum == 0) {
        printf("-1");
    } else {
        printf("%d", minSum);
    }

    return 0;
}


#include <stdio.h>

int mini(int a,int b){
    if(a>b){
        return b;
    }
    return a;
}

int main() {
    int n;
	scanf("%d",&n);
	int s[n],c[n];
	for(int i=0;i<n;i++){
	    scanf("%d",&s[i]);
	}
	for(int i=0;i<n;i++){
	    scanf("%d",&c[i]);
	}
	int min = 400000000;
	for(int i=1;i<n-1;i++){
	    int a = 400000000;
	    for(int j=0;j<i;j++){
	        if(s[j]<s[i]){
	            a = mini(a,c[j]);
	        }
	    }
	    int b = 400000000;
	    for(int j=i+1;j<n;j++){
	        if(s[i]<s[j]){
	            b = mini(b,c[j]);
	        }
	    }
	    min = mini(min,c[i]+a+b);

	}

	if(min==400000000){
	    printf("-1");
	    return 0;
	}
	printf("%d",min);
	return 0;
}


#include <stdio.h>

int mini(int a,int b){
    if(a>b){
        return b;
    }
    return a;
}

int main() {
    int n;
	scanf("%d",&n);
	int s[n],c[n];
	for(int i=0;i<n;i++){
	    scanf("%d",&s[i]);
	}
	for(int i=0;i<n;i++){
	    scanf("%d",&c[i]);
	}
	int min = 400000000;
	for(int i=0;i<n-2;i++){
	    for(int j=i+1;j<n-1;j++){
	        if(s[i]<s[j]){
	            for(int k=j+1;k<n;k++){
	                if(s[j]<s[k]){
	                    min = mini(min,c[i]+c[j]+c[k]);
	                }
	            }
	        }
	    }
	}
	if(min==400000000){
	    printf("-1");
	    return 0;
	}
	printf("%d",min);
	return 0;
}


#include<stdio.h>
long long min(long long a,long long b)
{
	if(a>b)
	return b;
	return a;
}
int main()
{
	int n;
	scanf("%d",&n);
	long long s[n],c[n];
	int i,j;
	int flag=0;
	for(i=0;i<n;i++)
	scanf("%lld",&s[i]);

	for(i=0;i<n;i++)
	scanf("%lld",&c[i]);

	long long mlr=-1;
	for(i=1;i<n-1;i++)
	{
	    long long ml=-1,mr=-1;

		for(j=i-1;j>=0;j--)
	       if(s[j]<s[i])
           {
           	  ml=c[j];
           	  break;
			}

		if(ml!=-1)
		for(j=i-1;j>=0;j--)
    		if(s[j]<s[i])
    		   ml=min(c[j],ml);

		for(j=i+1;j<n;j++)
	       if(s[j]>s[i])
           {
           	  mr=c[j];
           	  break;
			}
		if(mr!=-1&&ml!=-1)
    	for(j=i+1;j<n;j++)
    	    if(s[j]>s[i])
    		   mr=min(c[j],mr);

    	if(flag==0&&ml!=-1&&mr!=-1)
    	   { flag=1;
    	     mlr=ml+mr+c[i];
		   }
		else if(ml!=-1&&mr!=-1)
		   {
		   	  mlr=min(mlr,ml+mr+c[i]);
			}

	}

	printf("%lld",mlr);

	return 0;
}


#include<stdio.h>

long long int ara1[10000],ara2[10000],min=10000000000,n;

void foo(long long int i,long long int y,long long int sum,long long int x)
{
    long long int z;
    if(y==3){
        if(sum<min){
            min=sum;
        }
        return;
    }
    if(i==n){
        return;
    }
    if(ara1[i]>ara1[x]){
        z=sum+ara2[i];
        foo(i+1,y+1,z,i);
    }
    foo(i+1,y,sum,x);
}

int main()
{
    long long int i;
    scanf("%lld",&n);
    for(i=0;i<n;i++){
        scanf("%lld",&ara1[i]);
    }
    for(i=0;i<n;i++){
        scanf("%lld",&ara2[i]);

    }
    foo(0,0,0,-1);
    if(min==10000000000){
        printf("%d",-1);
    }
    else{
        printf("%lld",min);
    }
    //printf("\n%lld",ara1[-2]);
    return 0;

}


#include<stdio.h>

long long int ara1[10000],ara2[10000],min=10000000000,n;

void foo(long long int i,long long int y,long long int sum)
{
    long long int z;
    if(y==3){
        if(sum<min){
            min=sum;
        }
        return;
    }
    if(i==n){
        return;
    }
    if(ara1[i]>ara1[i-1]){
        z=sum+ara2[i];
        foo(i+1,y+1,z);
    }
    foo(i+1,y,sum);
}

int main()
{
    long long int i;
    scanf("%lld",&n);
    for(i=0;i<n;i++){
        scanf("%lld",&ara1[i]);
    }
    for(i=0;i<n;i++){
        scanf("%lld",&ara2[i]);

    }
    foo(0,0,0);
    if(min=10000000000){
        printf("%d",-1);
    }
    else{
        printf("%lld",min);
    }
    return 0;

}


#include<stdio.h>

long long int ara1[10000],ara2[10000],min=10000000000,n;

void foo(long long int i,long long int y,long long int sum)
{
    long long int z;
    if(y==3){
        if(sum<min){
            min=sum;
        }
        return;
    }
    if(i==n){
        return;
    }
    if(ara1[i]>ara1[i-1]){
        z=sum+ara2[i];
        foo(i+1,y+1,z);
    }
    foo(i+1,y,sum);
}

int main()
{
    long long int i;
    scanf("%lld",&n);
    for(i=0;i<n;i++){
        scanf("%lld",&ara1[i]);
    }
    for(i=0;i<n;i++){
        scanf("%lld",&ara2[i]);

    }
    foo(0,0,0);
    if(min==10000000000){
        printf("%d",-1);
    }
    else{
        printf("%lld",min);
    }
    return 0;

}


#include<stdio.h>

#define nax 3009

long long min(long long a,long long b){
	return a>b?b:a;
}

int main(){
	long long n,valor[nax],costo[nax],dp[nax][4];
	scanf("%lld",&n);
	for(int i= 0;i<n;i++){
		scanf("%lld",&valor[i]);
	}
	for(int i = 0 ; i<n;i++){
		scanf("%lld",&costo[i]);
	}

	for(int i= 0; i < n;i++){
		dp[i][1] = costo[i];
	}

	for(int j = 2; j < 4; j++){
		//primero lleno el dp[2] y luego el dp[3]
		for(int pos = 0; pos < n; pos++){
			long long costoNuevo = 10000000000000000LL;
			for(int i = 0 ; i < pos ; i++){
				if(valor[i]<valor[pos]){
					costoNuevo = min(costoNuevo,dp[i][j-1]+costo[pos]);
				}
			}
			dp[pos][j] = costoNuevo;
		}
	}

	long long rpta = 10000000000000000LL;
	for(int i = 0 ; i  < n ; i++){
		rpta = min(rpta,dp[i][3]);
	}
	if(rpta==10000000000000000LL){
		printf("-1");
	}else{
		printf("%lld",rpta);
	}

	return 0;
}


#include <stdlib.h>
#include <stdio.h>
#define  nax 3001
#define INF 30000000001
typedef long long lld;
lld Min(lld a , lld b){
	return a<b? a:b;
}
int main(){
	lld size;
	lld fsize[nax] , cost[nax],dp[nax][4];
	scanf("%lld",&size);
	for(int x=0;x<size;x++){
		scanf("%lld",&fsize[x]);
	}
	for(int y=0;y<size;y++){
		scanf("%lld",&cost[y]);
	}
	for(int k=0;k<size;k++){
		dp[k][1] = cost[k];
	}
	for(int i=2;i<4;i++){

		for(int pos=0;pos<size;pos++){
			dp[pos][i] = INF;
			for(int j=0;j<pos;j++){
				if (fsize[j] < fsize[pos]){
					dp[pos][i] = Min(dp[j][i-1]+cost[pos],dp[pos][i]);
				}
			}
		}
	}
	lld answ = INF;
	for(int i =0;i<size;i++){
		answ = Min(dp[i][3],answ);
	}
	if (answ == INF){
		printf("%i",-1);
	}else{
		printf("%lld",answ);
	}
}


#include <stdlib.h>
#include <stdio.h>
#define  nax 3001
#define INF 100000001
typedef long long lld;
lld Min(lld a , lld b){
	return a<b? a:b;
}
int main(){
	lld size;
	lld fsize[nax] , cost[nax],dp[nax][nax];
	scanf("%lld",&size);
	for(int x=0;x<size;x++){
		scanf("%lld",&fsize[x]);
	}
	for(int y=0;y<size;y++){
		scanf("%lld",&cost[y]);
	}
	for(int k=0;k<size;k++){
		dp[k][1] = cost[k];
	}
	for(int i=2;i<4;i++){

		for(int pos=0;pos<size;pos++){
			dp[pos][i] = INF;
			for(int j=0;j<pos;j++){
				if (fsize[j] < fsize[pos]){
					dp[pos][i] = Min(dp[j][i-1]+cost[pos],dp[pos][i]);
				}
			}
		}
	}
	lld answ = INF;
	for(int i =0;i<size;i++){
		answ = Min(dp[i][3],answ);
	}
	if (answ == INF){
		printf("%i",-1);
	}else{
		printf("%lld",answ);
	}
}


#include<stdio.h>
#include<stdlib.h>
#define INF 2147483646
int n, minLoc, ans=INF, s[3005]={}, c[3005]={}, dp[3005][4]={};
int min( int a, int b )
{
	return a>b ? b : a;
}
int main()
{
	scanf("%d", &n);
	for(int i=1; i<=n; i++) scanf("%d", &s[i]);
	for(int i=1; i<=n; i++) scanf("%d", &c[i]);
	for(int i=1; i<=n; i++)
		dp[i][1] = dp[i][2] = dp[i][3] =INF; //初始化
	for(int i=1; i<=n; i++){ //选i
		for(int j=1; j<i; j++){ //满足j<i
			if( s[j] < s[i] ){
					dp[i][2] = min( dp[i][2], c[i]+c[j] );
					if( dp[j][2] < INF )
						dp[i][3] = min( dp[i][3], dp[j][2]+c[i] );
			}
		}
	}
	for(int i=1; i<=n; i++)
		ans = min( ans, dp[i][3] );
	if( ans==INF ) ans = -1; //ans没更新说明没有符合条件的三元组
	printf("%d\n", ans);
	//system("pause");
	return 0;
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace displays
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            n = Convert.ToInt32(Console.ReadLine());

            int[] s = new int[n];
            int[] c = new int[n];

            string[] sor = Console.ReadLine().Split(' ');

            for (int i = 0; i < n; i++)
            {
                s[i] = Convert.ToInt32(sor[i]);
            }
            sor = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
            {
                c[i] = Convert.ToInt32(sor[i]);
            }

            List<int> jok = new List<int>();

            for (int i = 0; i < n; i++)
            {
                int m = int.MaxValue;
                for (int j = i + 1; j < n; j++)
                {
                    if (s[i] < s[j] && c[j] < m)
                    {
                        m = c[j];
                    }
                }
                jok.Add(m);
            }

            int min = int.MaxValue;

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if (s[i] < s[j] && jok[j] != int.MaxValue)
                    {
                        int value = c[i] + c[j] + jok[j];
                        if (value < min)
                        {
                            min = value;
                        }
                    }
                }
            }

            if(min == int.MaxValue)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(min);
            }

            Console.ReadLine();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace displays
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            n = Convert.ToInt32(Console.ReadLine());

            int[] s = new int[n];
            int[] c = new int[n];

            string[] sor = Console.ReadLine().Split(' ');

            for (int i = 0; i < n; i++)
            {
                s[i] = Convert.ToInt32(sor[i]);
            }
            sor = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
            {
                c[i] = Convert.ToInt32(sor[i]);
            }

            List<List<int>> jok = new List<List<int>>();

            for (int i = 0; i < n; i++)
            {
                jok.Add(new List<int>());
                for (int j = i + 1; j < n; j++)
                {
                    if(s[i]<s[j])
                    {
                        jok[i].Add(c[j]);
                    }
                }
                jok[i].Sort();
            }

            int min = int.MaxValue;

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if (jok[j].Count > 0)
                    {
                        if (s[i] < s[j])
                        {
                            int value = c[i] + c[j] + jok[j][0];
                            if (value < min)
                            {
                                min = value;
                            }
                        }
                    }
                }
            }

            if(min == int.MaxValue)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(min);
            }

            Console.ReadLine();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace displays
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            n = Convert.ToInt32(Console.ReadLine());

            int[] s = new int[n];
            int[] c = new int[n];

            string[] sor = Console.ReadLine().Split(' ');

            for (int i = 0; i < n; i++)
            {
                s[i] = Convert.ToInt32(sor[i]);
            }
            sor = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
            {
                c[i] = Convert.ToInt32(sor[i]);
            }

            int min = int.MaxValue;

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    for (int k = j + 1; k < n; k++)
                    {
                        if(s[i] < s[j] && s[j] < s[k])
                        {
                            int v = c[i] + c[j] + c[k];
                            if (v < min)
                            {
                                min = v;
                            }
                        }
                    }
                }
            }

            if(min == int.MaxValue)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(min);
            }
        }
    }
}


using System;
using System.Linq;

namespace CSharp
{
    class _987C
    {
        public static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            int[] s = Console.ReadLine().Split().Select(token => int.Parse(token)).ToArray();
            int[] c = Console.ReadLine().Split().Select(token => int.Parse(token)).ToArray();

            int[] left = new int[n];
            int[] right = new int[n];

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if (s[i] < s[j])
                    {
                        if (right[i] == 0 || c[j] < right[i])
                        {
                            right[i] = c[j];
                        }

                        if (left[j] == 0 || c[i] < left[j])
                        {
                            left[j] = c[i];
                        }
                    }
                }
            }

            Console.WriteLine(Enumerable.Range(0, n).Where(i => left[i] > 0 && right[i] > 0).Select(i => left[i] + c[i] + right[i]).DefaultIfEmpty(-1).Min());
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces2905C
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int nn = n;
            string read;

            List<int> slist = new List<int>();
            List<int> clist = new List<int>();

            read = Console.ReadLine();
            slist = (read.Split(' ').ToList()).Select(s => int.Parse(s)).ToList();

            read = Console.ReadLine();
            clist = (read.Split(' ').ToList()).Select(s => int.Parse(s)).ToList();

            int[] paircost = new int[3002];
            Dictionary<int, bool> valid = new Dictionary<int, bool>();

            for (int i = 0; i < n; i++)
            {
                paircost[i] = clist[i];
                valid.Add(i, false);
            }

            int min = int.MaxValue;
            bool found = false;

            for (int i = 0; i < n; i++)
            {
                min = int.MaxValue;
                found = false;
                for (int j = i + 1; j < n; j++)
                {
                    if (slist[i] < slist[j])
                    {
                        if (min > clist[j])
                        {
                            min = clist[j];
                            found = true;
                        }
                    }
                }

                if (found)
                {
                    paircost[i] = paircost[i] + min;
                    valid[i] = true;
                }
            }

            valid[0] = false;
            valid[n - 1] = false;

            int outputmin = int.MaxValue;
            bool outputfound = false;

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if(valid[j] && slist[i] < slist[j])
                    {
                        outputfound = true;
                        if(outputmin > clist[i] + paircost[j])
                        {
                            outputmin = clist[i] + paircost[j];
                        }
                    }
                }
            }

            if(outputfound)
            {
                Console.WriteLine(outputmin);
            }
            else
            {
                Console.WriteLine("-1");
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var size = Console.ReadLine().Split().Select(int.Parse).ToList();
        var cost = Console.ReadLine().Split().Select(int.Parse).ToList();

        var result = new ResultNode3(-1, -1, -1); ;

        if (n >= 3)
        {
            var onesIndexes = GetOnesIndexes(size, cost, n);

            var twosIndexes = GetTwosIndexes(size, cost, onesIndexes, n);
            var first = true;

            for (int i = 0; i < n; i++)
            {

                if (first && twosIndexes[i].IsValid())
                {
                    result = new ResultNode3(twosIndexes[i].Index1, twosIndexes[i].Index2, i);
                    first = false;
                }
                else
                {
                    var twos = twosIndexes[i];
                    if (result.IsValid() && twos.IsValid() && result.GetCost(cost) > (cost[i] + twos.GetCost(cost)))
                    {
                        result = new ResultNode3(twos.Index1, twos.Index2, i);
                    }
                }

            }
        }

        Console.WriteLine(result.GetCost(cost));
    }

    private static List<ResultNode2> GetTwosIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int n)
    {
        var result = new List<ResultNode2>();

        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostCoupleIndexes(size, cost, onesIndexes, i, n));
        }

        return result;
    }

    private static ResultNode2 GetMinCostCoupleIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int upperLimitIndex, int n)
    {
        var upperLimitSize = size[upperLimitIndex];

        var resultNode2 = new ResultNode2(-1, -1);
        var first = true;

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (size[i] >= upperLimitSize)
                continue;

            if (first && onesIndexes[i] != -1)
            {
                resultNode2 = new ResultNode2(onesIndexes[i], i);
                first = false;
            }
            else
            {
                if (resultNode2.IsValid() && onesIndexes[i] != -1 && resultNode2.GetCost(cost) > (cost[i] + cost[onesIndexes[i]]))
                {
                    resultNode2 = new ResultNode2(onesIndexes[i], i);
                }
            }
        }

        return resultNode2;
    }

    private static List<int> GetOnesIndexes(List<int> size, List<int> cost, int n)
    {
        var result = new List<int>();
        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostElemIndex(size, cost, i, n));
        }

        return result;
    }

    private static int GetMinCostElemIndex(List<int> size, List<int> cost, int upperLimitIndex, int n)
    {
        var min = int.MaxValue;
        var minIndex = -1;
        var upperLimitSize = size[upperLimitIndex];

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (cost[i] < min && size[i] < upperLimitSize)
            {
                min = cost[i];
                minIndex = i;
            }
        }

        return minIndex;
    }

}

internal class ResultNode2
{
    public int Index1;
    public int Index2;

    public bool IsValid()
    {
        return Index1 != -1 && Index2 != -1;
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2];
        }

        return -1;
    }

    public ResultNode2(int index1, int index2)
    {
        Index1 = index1;
        Index2 = index2;
    }
}

internal class ResultNode3
{
    public int Index1;
    public int Index2;
    public int Index3;

    internal bool IsValid()
    {
        return Index1 != -1 && Index2 != -1 && Index3 != -1;
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2] + cost[Index3];
        }

        return -1;
    }

    public ResultNode3(int index1, int index2, int index3)
    {
        Index1 = index1;
        Index2 = index2;
        Index3 = index3;
    }

}


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var size = Console.ReadLine().Split().Select(int.Parse).ToList();
        var cost = Console.ReadLine().Split().Select(int.Parse).ToList();

        var result = new ResultNode3(-1, -1, -1); ;

        if (n >= 3)
        {
            var onesIndexes = GetOnesIndexes(size, cost, n);

            var twosIndexes = GetTwosIndexes(size, cost, onesIndexes, n);

            for (int i = 0; i < n; i++)
            {
                if (result.CanSet(size, i))
                {
                    result.Set(i);
                }
                else
                {
                    var twos = twosIndexes[i];
                    if (result.IsValid() && result.GetCost(cost) > (cost[i] + twos.GetCost(cost)))
                    {
                        result = new ResultNode3(twos.Index1, twos.Index2, i);
                    }
                }

            }
        }

        Console.WriteLine(result.GetCost(cost));
    }

    private static List<ResultNode2> GetTwosIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int n)
    {
        var result = new List<ResultNode2>();

        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostCoupleIndexes(size, cost, onesIndexes, i, n));
        }

        return result;
    }

    private static ResultNode2 GetMinCostCoupleIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int upperLimitIndex, int n)
    {
        var upperLimitSize = size[upperLimitIndex];

        var resultNode2 = new ResultNode2(-1, -1);

        for (int i = 0; i < n; i++)
        {
            if (size[i] >= upperLimitSize)
                continue;

            if (resultNode2.CanSet(size, i))
            {
                resultNode2.Set(i);
            }
            else
            {
                if (resultNode2.IsValid() && onesIndexes[i] != -1 && resultNode2.GetCost(cost) > (cost[i] + cost[onesIndexes[i]]))
                {
                    resultNode2 = new ResultNode2(onesIndexes[i], i);
                }
            }
        }

        return resultNode2;
    }

    private static List<int> GetOnesIndexes(List<int> size, List<int> cost, int n)
    {
        var result = new List<int>();
        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostElemIndex(size, cost, i, n));
        }

        return result;
    }

    private static int GetMinCostElemIndex(List<int> size, List<int> cost, int upperLimitIndex, int n)
    {
        var min = cost.Max();
        var minIndex = -1;
        var upperLimitSize = size[upperLimitIndex];

        for (int i = 0; i < n; i++)
        {
            if (cost[i] < min && size[i] < upperLimitSize)
            {
                min = cost[i];
                minIndex = i;
            }
        }

        return minIndex;
    }

    private static int CalculateCost(int a, int b, int c, List<int> size, List<int> cost)
    {
        if (a < b && b < c && size[a] < size[b] && size[b] < size[c])
        {
            return cost[a] + cost[b] + cost[c];
        }

        return -1;
    }

}

internal class ResultNode2
{
    public int Index1;
    public int Index2;

    public bool IsValid()
    {
        return Index1 != -1 && Index2 != -1;
    }

    public bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]);
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2];
        }

        return -1;
    }

    public void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;
        }
        else
        {
            Index2 = index;
        }
    }

    public ResultNode2(int index1, int index2)
    {
        Index1 = index1;
        Index2 = index2;
    }
}

internal class ResultNode3
{
    public int Index1;
    public int Index2;
    public int Index3;

    internal bool IsValid()
    {
        return Index1 != -1 && Index2 != -1 && Index3 != -1;
    }

    internal bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]) || (Index2 != -1 && Index3 == -1 && size[Index2] < size[i]);
    }

    internal void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;

            return;
        }

        if (Index2 == -1)
        {
            Index2 = index;

            return;
        }

        if (Index3 == -1)
        {
            Index3 = index;

            return;
        }
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2] + cost[Index3];
        }

        return -1;
    }

    public ResultNode3(int index1, int index2, int index3)
    {
        Index1 = index1;
        Index2 = index2;
        Index3 = index3;
    }

}