from collections import defaultdict

l = raw_input()
l = l.strip().split(" ")
n = int(l[0])
m = int(l[1])
prices = [int(x) for x in raw_input().strip().split(" ")]

matches = defaultdict(list)

for i in range(0, m):
    xy = raw_input().strip().split(" ")
    x = int(xy[0])
    y = int(xy[1])
    matches[x].append(y)
    matches[y].append(x)

res = float("inf")

for key in matches.keys():
    for a in matches[key]:
        for b in matches.get(a, []):
            for c in matches.get(b, []):
                if a in matches.get(c, []):
                    res = min(res, prices[a-1]+prices[b-1]+prices[c-1])

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


n, m = tuple(int(x) for x in raw_input().strip().split(" "))
prices = [int(x) for x in raw_input().strip().split(" ")]

matches = [[False]*n for i in range(0, n)]

for i in range(0, m):
    x, y = tuple(int(x) for x in raw_input().strip().split(" "))
    matches[x-1][y-1] = True
    matches[y-1][x-1] = True

inf = float("inf")
result = inf
for i in range(0, n):
    for j in range(i+1, n):
        for k in range(j+1, n):
            if matches[i][j] and matches[j][k] and matches[k][i]:
                result = min(result, prices[i]+prices[j]+prices[k])

if result==inf:
    print -1
else:
    print result


#! /usr/bin/env python

from sys import stdin
INF=10**18

def solve(graph,prices):
	N=len(graph)
	ret=INF
	for a in xrange(N):
		for b in xrange(a+1,N):
			if graph[a][b]:
				for c in xrange(b+1,N):
					if graph[a][c] and graph[b][c]:
						ret=min(ret,prices[a]+prices[b]+prices[c])

	if ret==INF:
		ret=-1
	return ret

if __name__=='__main__':
	n,m=map(int,stdin.readline().split())
	graph=[[False for i in xrange(n)] for j in xrange(n)]
	prices=map(int,stdin.readline().split())
	for edge in xrange(m):
		u,v=map(int,stdin.readline().split())
		u-=1;v-=1
		graph[u][v]=True
		graph[v][u]=True
	print solve(graph,prices)


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = [[False] * n for x in range n]
for i in range(m):
    x, y = map(int, raw_input().split())
    b[x-1][y-1] = b[y-1][x-1] = True
best = 10000000
for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if b[i][j] and b[j][k] and b[i][k]:
                if a[i] + a[j] + a[k] < best:
                    best = a[i] + a[j] + a[k]
if best == 10000000:
    best = -1
print best


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = [[False] * n for x in range(n)]
for i in range(m):
    x, y = map(int, raw_input().split())
    b[x-1][y-1] = b[y-1][x-1] = True
best = 10000000
for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if b[i][j] and b[j][k] and b[i][k]:
                if a[i] + a[j] + a[k] < best:
                    best = a[i] + a[j] + a[k]
if best == 10000000:
    best = -1
print best


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = []
for i in range(m):
    x, y = map(int, raw_input().split())
    b.append((x - 1, y - 1))
    b.append((y - 1, x - 1))
best = 10000000
for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if (i, j) in b and (j, k) in b and (i, k) in b:
                if a[i] + a[j] + a[k] < best:
                    best = a[i] + a[j] + a[k]
if best == 10000000:
    best = -1
print best


n,m=[int(x) for x in raw_input().split()]
cost=[int(x) for x in raw_input().split()]
s=[]
lst=[list(s) for x in xrange(n)]
for i in xrange(m):
    z,y=[int(x) for x in raw_input().split()]
    lst[z-1].append(y)
    lst[y-1].append(z)
fincost=[]
for i in xrange(n):
  if len(lst[i])>1:
    for j in lst[i]:
        for poisk in lst[j-1]:
            if poisk in lst[i]:
                fincost.append(cost[i]+cost[j-1]+cost[poisk-1])
print [min(fincost),'-1'][len(fincost)==0]


import copy
n,m=[int(x) for x in raw_input().split()]
cost=[int(x) for x in raw_input().split()]
s=[]
lst=[]
lst=[list(s) for x in xrange(n)]
for i in xrange(m):
    z,y=[int(x) for x in raw_input().split()]
    lst[z-1].append(y)
    lst[y-1].append(z)
fincost=[]
for i in xrange(n):
  if len(lst[i])>1:
    for j in lst[i]:
      if j-1>i:
        for poisk in lst[j-1]:
            if poisk in lst[i]:
                fincost.append(cost[i]+cost[j-1]+cost[poisk-1])
if len(fincost)==0:
    print ('-1')
else:
    print (min(fincost))


import copy
n,m=[int(x) for x in raw_input().split()]
cost=[int(x) for x in raw_input().split()]
s=[]
lst=[]
lst=[list(s) for x in xrange(n)]
for i in xrange(m):
    z,y=[int(x) for x in raw_input().split()]
    lst[z-1].append(y)
    lst[y-1].append(z)
fincost=[]
for i in xrange(n):
  if len(lst[i])>1:
    for j in lst[i]:
      if j-1>i:
        for poisk in lst[j-1]:
            if poisk in lst[i]:
                fincost.append(cost[i]+cost[j-1]+cost[poisk-1])
print [min(fincost),'-1'][len(fincost)==0]


import itertools

n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
g = {}
for i in range(m):
    u, v = map(int, raw_input().split())
    u -= 1
    v -= 1
    g[(u, v)] = True
    g[(v, u)] = True
m = 10000000
for x in itertools.combinations(range(0, n), 3):
    if (x[0], x[1]) in g and  (x[1], x[2]) in g and (x[2], x[0]) in g:
        v = a[x[0]] + a[x[1]] + a[x[2]]
        if v < m:
            m = v
if m == 10000000:
    print -1
else:
    print m


n, m = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())

if m < 3:
    print -1
    exit()

k = 0
for i in range(1,m):
    k = k+i

if m != k:
    print -1
else:
    print sum(a)


n , m = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())
b = []
for i in range(n):
    b.append([False]*n)
for i in range(m):
    x, y= map(int, raw_input().strip().split())
    x = x - 1
    y = y - 1
    b[x][y] = b[y][x] = True
mini=100000000
for i in range(10):
    for i in range(n):
        for j in range(i+1,n):
            if(b[i][j]):
                for k in range(j+1,n):
                    if b[i][k] and b[j][k]:
                        summ=a[i]+a[j]+a[k]
                        if summ<mini:
                            mini=summ
if mini==100000000:
    mini = -1
print mini


s=raw_input().split()
n=int(s[0])
m=int(s[1])
pri=[int(x) for x in raw_input().split()]
rel=[set() for x in range(n)]
for i in range(m):
	s=raw_input().split()
	a=int(s[0])-1
	b=int(s[1])-1
	rel[a].add(b)
	rel[b].add(a)
rpta=1<<30
for i in range(n):
	for j in range(i+1,n):
		for k in range(j+1,n):
			if i in rel[j] and i in rel[k] and j in rel[k]:
				rpta=min(rpta,pri[i]+pri[j]+pri[k])
if rpta!=1<<30:
	print rpta
else:
	print -1


s=raw_input().split()
n=int(s[0])
m=int(s[1])
pri=[int(x) for x in raw_input().split()]
rel=[-1]*n
for i in range(m):
	s=raw_input().split()
	rel[int(s[0])-1]=int(s[1])-1
rpta=1<<30
for i in range(n):
	if rel[i]!=-1 and rel[rel[i]]!=-1 and rel[rel[rel[i]]]!=-1 and \
		i==rel[rel[rel[i]]] and i!=rel[rel[i]]:
		rpta=min(rpta,pri[i]+pri[rel[i]]+pri[rel[rel[i]]])
if rpta!=1<<30:
	print rpta
else:
	print -1


#!/usr/bin/env python

n,m=[int(x) for x in raw_input().split()]
a=[int(x) for x in raw_input().split()]
b=[]
for i in range(n):
	b.append([False]*n)
for i in range(m):
	x,y=[int(x) for x in raw_input().split()]
	x-=1
	y-=1
	b[x][y]=b[y][x]=True
min_=100000000
for i in range(n):
	for j in range(i+1,n):
		if(b[i][j]):
			for k in range(j+1,n):
				if b[i][k] and b[j][k]:
					sum_=a[i]+a[j]+a[k]
					if sum_<min_:
						min_=sum_
if min_==100000000:
	min_=-1
print min_


#!/usr/bin/env python

n,m=[int(x) for x in raw_input().split()]
a=[int(x) for x in raw_input().split()]
b=[]
for i in range(n):
	b.append([False]*n)
for i in range(m):
	x,y=[int(x) for x in raw_input().split()]
	x-=1
	y-=1
	b[x][y]=b[y][x]=True
min_=100000000
for i in range(20):
	for i in range(n):
		for j in range(i+1,n):
			if(b[i][j]):
				for k in range(j+1,n):
					if b[i][k] and b[j][k]:
						sum_=a[i]+a[j]+a[k]
						if sum_<min_:
							min_=sum_
if min_==100000000:
	min_=-1
print min_


#!/usr/bin/env python

n,m=[int(x) for x in raw_input().split()]
a=[int(x) for x in raw_input().split()]
b=[]
for i in range(n):
	b.append([False]*n)
for i in range(m):
	x,y=[int(x) for x in raw_input().split()]
	x-=1
	y-=1
	b[x][y]=b[y][x]=True
min_=100000000
for i in range(10):
	for i in range(n):
		for j in range(i+1,n):
			if(b[i][j]):
				for k in range(j+1,n):
					if b[i][k] and b[j][k]:
						sum_=a[i]+a[j]+a[k]
						if sum_<min_:
							min_=sum_
if min_==100000000:
	min_=-1
print min_


from itertools import combinations
n,m=map(int,raw_input().split())
p=map(int,raw_input().split())

mm=[0]*n*n
for _ in range(m):
  x,y=map(lambda x:int(x)-1,raw_input().split())
  mm[x*n+y]=mm[y*n+x]=1
mn=100000000
for c in combinations(range(n),3):
  if mm[c[0]*n+c[1]]+mm[c[0]*n+c[2]]+mm[c[1]*n+c[2]]==3:
    mn = min(mn, p[c[0]]+p[c[1]]+p[c[2]])
print mn if mn<100000000 else -1


from itertools import combinations

def jn(c): return sorted(set(c[0]+c[1]+c[2]))
def sm(c): return p[c[0]-1]+p[c[1]-1]+p[c[2]-1]

n,m=map(int,raw_input().split())
p=map(int,raw_input().split())
a=[map(int,raw_input().split()) for _ in range(m)]

aa = filter(lambda x:len(x)==3,[jn(c) for c in combinations(a,3)])

if len(aa)>0: print min(map(sm,aa))
else: print -1


from itertools import combinations
n,m=map(int,raw_input().split())
p=map(int,raw_input().split())
a=[sorted(map(int,raw_input().split())) for _ in range(m)]

def ex(t,x,y):return a.count([t[x]+1,t[y]+1])==1
def sump(t):
  if ex(t,0,1) and ex(t,0,2) and ex(t,1,2):return sum(map(lambda x:p[x],t))
  else:return -1

ss = filter(lambda x:x>=0,[sump(c) for c in combinations(range(n),3)])
if len(ss)==0: print -1
else: print min(ss)


import sys
n,m=map(int,sys.stdin.readline().split())

C=list(map(int,sys.stdin.readline().split()))

E=[]
for i in range(101):
    E.append([False]*(n+1))

for i in range(m):
    x,y=map(int,sys.stdin.readline().split())
    E[x][y]=True
    E[y][x]=True

minn=10**10
for x in range(1,n+1):
    for y in range(1,n+1):
        if(x==y):
            continue
        for z in range(1,n+1):
            if(x==z or y==z):
                continue
            if(E[x][y] and E[x][z] and E[y][z]):
                ans=C[x-1]+C[y-1]+C[z-1]
                if(ans<minn):
                    minn=ans
if(minn==10**10):
    minn=-1
sys.stdout.write(str(minn))


INF = 1000000000

L1 = map(int,raw_input().strip().split())

n = L1[0]
m = L1[1]

ism = [[0 for i in range(n)] for i in range(n)]

p = map(int,raw_input().strip().split())

for i in range(m):
    L = map(int,raw_input().strip().split())
    ism[L[0] - 1][L[1] - 1] = 1
    ism[L[1] - 1][L[0] - 1] = 1

answer = INF

for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if ism[i][j] and ism[j][k] and ism[i][k]:
                answer = min(answer, p[i] + p[j] + p[k])

if answer == INF:
    print -1
else:
    print answer


n,m=map(int,raw_input().split())
cost=map(int,raw_input().split())

a=[[0 for i in xrange(n)] for j in xrange(n)]

for i in xrange(m):
    q1,q2=map(int,raw_input().split())
    a[q1-1][q2-1]=1
    a[q2-1][q1-1]=1

min1=10**10

for i in xrange(n):
    for j in xrange(n):
        for k in xrange(n):
            if a[i][j]==1 and a[j][k]==1 and a[k][i]==1:
                min1=min(min1,cost[i]+cost[j]+cost[k])
if min1==10**10:min1=-1
print min1


#import sys
#sys.stdin = open("input.in")
n, m = map(int, raw_input().split(' '))
p = map(int, raw_input().split(' '))
a = [[0 for i in xrange(n)] for j in xrange(n)]
for i in xrange(m):
	u, v = map(int, raw_input().split(' '))
	a[u - 1][v - 1] = a[v - 1][u - 1] = 1
res = 100000000
for i in xrange(n):
	for j in xrange(n):
		for k in xrange(n):
			if a[i][j] and a[j][k] and a[k][i]:
				if p[i] + p[j] + p[k] < res:
					res = p[i] + p[j] + p[k]
print res if res < 100000000 else -1


#import sys
#sys.stdin = open("input.in")
n, m = map(int, raw_input().split())
p = map(int, raw_input().split())
a = [[0] * n for j in xrange(n)]
for i in xrange(m):
	u, v = map(int, raw_input().split())
	a[u - 1][v - 1] = a[v - 1][u - 1] = 1
res = 100000000
for i in xrange(n):
	for j in xrange(i + 1, n):
		for k in xrange(j + 1, n):
			if a[i][j] and a[j][k] and a[k][i]:
				if p[i] + p[j] + p[k] < res:
					res = p[i] + p[j] + p[k]
print res if res < 100000000 else -1


f = lambda : map(int, raw_input().split())
n, m = f()
p = f()
a = [[0] * n for j in xrange(n)]
for i in xrange(m):
	u, v = f()
	a[u - 1][v - 1] = a[v - 1][u - 1] = 1
res = 1 << 30
for i in xrange(n):
	for j in xrange(i + 1, n):
		for k in xrange(j + 1, n):
			if a[i][j] and a[j][k] and a[k][i]: res = min(res, p[i] + p[j] + p[k])
print res if res < 1 << 30 else -1


f = lambda : map(int, raw_input().split())
n, m = f()
p = f()
a = [[0] * n for j in xrange(n)]
for i in xrange(m):
	u, v = f()
	a[u - 1][v - 1] = a[v - 1][u - 1] = 1
res = 100000000
for i in xrange(n):
	for j in xrange(i + 1, n):
		for k in xrange(j + 1, n):
			if a[i][j] and a[j][k] and a[k][i]: res = min(res, p[i] + p[j] + p[k])
print res if res < 100000000 else -1


#import sys
#sys.stdin = open("input.in")
n, m = map(int, raw_input().split())
p = map(int, raw_input().split())
a = [[0] * n for j in xrange(n)]
for i in xrange(m):
	u, v = map(int, raw_input().split())
	a[u - 1][v - 1] = a[v - 1][u - 1] = 1
res = 100000000
for i in xrange(n):
	for j in xrange(n):
		for k in xrange(n):
			if a[i][j] and a[j][k] and a[k][i]:
				if p[i] + p[j] + p[k] < res:
					res = p[i] + p[j] + p[k]
print res if res < 100000000 else -1


r=lambda:map(int,raw_input().split())
n,m=r()
A=r()
p=[[] for i in range(n)]
for i in range(m):
    a,b=r()
    a,b=a-1,b-1
    p[a]+=[b]
    p[b]+=[a]

s=set()
for i,l in enumerate(p):
     for a in l:
        for b in l:
            if a != b and a in p[b]:
                s.add(tuple(sorted((i,a,b))))
print min( A[a]+A[b]+A[c] for (a,b,c) in s) if s else -1


r=lambda:map(int,raw_input().split())
n,m=r()
A=r()
p=[[] for i in range(n)]
for i in range(m):
    a,b=r()
    a,b=a-1,b-1
    a,b=min(a,b),max(a,b)
    p[a]+=[b]

s=set()
m=10**8
for i,l in enumerate(p):
     for j in range(len(l)-1):
         for k in range(j+1,len(l)):
            a,b=l[j],l[k]
            a,b=min(a,b),max(a,b)
            if b in p[a]:
                s=A[i]+A[b]+A[a]
                m=min(s,m)

print m if m != 10**8 else -1


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = [[0] * n for _ in range(n)]
for _ in range(m):
	x, y = map(int, raw_input().split())
	b[x - 1][y - 1] = b[y - 1][x - 1] = 1
r = [a[i] + a[j] + a[k] for i in range(n) for j in range(n) for k in range(n) if b[i][j] and b[i][k] and b[j][k]]
print min(r) if len(r) else -1


r=lambda: map(int,raw_input().split())
n,m=r()
a=r()
rn=range(n)
l=[[0]*n for i in rn]
for i in range(m):
	v,u=r()
	v-=1
	u-=1
	l[u][v]=l[v][u]=1
mx=10**10
an=mx
for i in rn:
	for j in range(i+1,n):
		for k in range(j+1,n):
			if l[i][j] and l[j][k] and l[k][i]:
				an=min(an,a[i]+a[j]+a[k])
print -1 if an==mx else an


n, m = (int(x) for x in raw_input().split())
v = [int(x) for x in raw_input().split()]
mp = [[0 for j in range(0, n)] for i in range(0, n)]
for i in xrange(0, m):
    a, b = map(int, raw_input().split())
    mp[a - 1][b - 1] = 1
    mp[b - 1][a - 1] = 1

mn = 10000000
for i in range(0, n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if mp[i][j] and mp[i][k] and mp[j][k]:
                if mn > (v[i] + v[j] + v[k]):
                    mn = v[i] + v[j] + v[k]

if mn < 10000000:
    print mn
else:
    print -1


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
input = sys.stdin
output = sys.stdout

int_inf_pos = sys.maxint
int_inf_neg = -sys.maxint - 1

from collections import defaultdict
from itertools import combinations

def solve(C,P):

    G = defaultdict(lambda: set())
    for p in P:
        u,v = p
        G[u].add(v)
        G[v].add(u)

    min_cost = sys.maxint
    solution_found = False

    for t in combinations(range(n), 3):
        x,y,z = t
        triple_allowed = y in G[x] and z in G[y] and x in G[z]
        if triple_allowed:
            solution_found = True
            cost = C[x] + C[y] + C[z]
            if min_cost > cost:
                min_cost = cost

    if not solution_found:
        return -1

    return min_cost

def numbers_from_line(d=' '):
    return [int(s) for s in input.readline().strip().split(d) if len(s.strip())>0]

n,m = tuple(numbers_from_line())

C = numbers_from_line()

P = []
for _ in range(m):
    u,v = tuple(numbers_from_line())
    P.append((u-1,v-1))

a = solve(C,P)
output.write('%d\n' % a)


# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"

if __name__ == "__main__":
    inp = raw_input()
    input = inp.rsplit(' ')
    n = int(input[0])
    m = int(input[1])
    arrprice = []
    inp = raw_input()
    input = inp.rsplit(' ')
    for i in range(0,n):
        arrprice.append(int(input[i]))

    arrpairs = [0] * n
    for i in range(n):
        arrpairs[i] = []

    for i in range(0,m):
        inp = raw_input()
        input = inp.rsplit(' ')
        x = int(input[0])
        y = int(input[1])
        arrpairs[x-1].append(y)
        arrpairs[y-1].append(x)

    minprice = -1
    first = 1
    for i in range(0,m):
        for j in arrpairs[i]:
            for k in arrpairs[j-1]:
                if (i+1 in arrpairs[k-1]) and (arrprice[i]+arrprice[j-1]+arrprice[k-1]<minprice or first==1):
                    first = 0
                    minprice = arrprice[i]+arrprice[j-1]+arrprice[k-1]

    print minprice


# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"

if __name__ == "__main__":
    inp = raw_input()
    input = inp.rsplit(' ')
    n = int(input[0])
    m = int(input[1])
    arrprice = []
    inp = raw_input()
    input = inp.rsplit(' ')
    for i in range(0,n):
        arrprice.append(int(input[i]))

    arrpairs = [0] * n
    for i in range(n):
        arrpairs[i] = []

    for i in range(0,m):
        inp = raw_input()
        input = inp.rsplit(' ')
        x = int(input[0])
        y = int(input[1])
        arrpairs[x-1].append(y)

    minprice = -1
    first = 1
    for i in range(0,m):
        for j in arrpairs[i]:
            for k in arrpairs[j-1]:
                if (i+1 in arrpairs[k-1]) and (arrprice[i]+arrprice[j-1]+arrprice[k-1]<minprice or first==1):
                    first = 0
                    minprice = arrprice[i]+arrprice[j-1]+arrprice[k-1]

    print minprice


# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"

if __name__ == "__main__":
    inp = raw_input()
    input = inp.rsplit(' ')
    n = int(input[0])
    m = int(input[1])
    arrprice = []
    inp = raw_input()
    input = inp.rsplit(' ')
    for i in range(0,n):
        arrprice.append(int(input[i]))

    arrpairs = [0] * n
    for i in range(n):
        arrpairs[i] = []

    for i in range(0,m):
        inp = raw_input()
        input = inp.rsplit(' ')
        x = int(input[0])
        y = int(input[1])
        arrpairs[x-1].append(y)
        arrpairs[y-1].append(x)

    minprice = -1
    price = ''
    first = 1

    for i in range(0,m):
        price = arrprice[i]
        if (price<minprice or first==1):
            for j in arrpairs[i]:
                price  = arrprice[i]+arrprice[j-1]
                if (price<minprice or first==1):
                    for k in arrpairs[j-1]:
                        price = arrprice[i]+arrprice[j-1]+arrprice[k-1]
                        if (i+1 in arrpairs[k-1]) and (price<minprice or first==1):
                            first = 0
                            minprice = price

    print minprice


# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"

if __name__ == "__main__":
    inp = raw_input()
    input = inp.rsplit(' ')
    n = int(input[0])
    m = int(input[1])
    arrprice = []
    inp = raw_input()
    input = inp.rsplit(' ')
    for i in range(0,n):
        arrprice.append(int(input[i]))

    arrpairs = [0] * n
    for i in range(n):
        arrpairs[i] = []

    for i in range(0,m):
        inp = raw_input()
        input = inp.rsplit(' ')
        x = int(input[0])
        y = int(input[1])
        arrpairs[x-1].append(y)
        arrpairs[y-1].append(x)

    minprice = -1
    price = ''
    first = 1

    for i in range(0,m):
        t = 0
        price = arrprice[i]
        if (price<minprice or first==1):
            for j in arrpairs[i]:
                price  = arrprice[i]+arrprice[j-1]
                if (price<minprice or first==1)and j!=i:
                    for k in arrpairs[j-1]:
                        price = arrprice[i]+arrprice[j-1]+arrprice[k-1]
                        if (price<minprice or first==1)and(i+1 in arrpairs[k-1]):
                            first = 0
                            minprice = price
                            t = 1
                            break
                if (t==1): break
    print minprice


# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"

if __name__ == "__main__":
    inp = raw_input()
    input = inp.rsplit(' ')
    n = int(input[0])
    m = int(input[1])
    arrprice = []
    inp = raw_input()
    input = inp.rsplit(' ')
    for i in range(0,n):
        arrprice.append(int(input[i]))

    arrpairs = [0] * n
    for i in range(n):
        arrpairs[i] = []

    for i in range(0,m):
        inp = raw_input()
        input = inp.rsplit(' ')
        x = int(input[0])
        y = int(input[1])
        arrpairs[x-1].append(y)
        arrpairs[y-1].append(x)

    minprice = -1
    price = ''
    first = 1

    for i in range(0,m):
        t = 0
        price = arrprice[i]
        if (price<minprice or first==1):
            for j in arrpairs[i]:
                price  = arrprice[i]+arrprice[j-1]
                if (price<minprice or first==1):
                    for k in arrpairs[j-1]:
                        price = arrprice[i]+arrprice[j-1]+arrprice[k-1]
                        if (i+1 in arrpairs[k-1]) and (price<minprice or first==1):
                            first = 0
                            minprice = price
                            t = 1
                            break
                if (t==1): break
    print minprice


# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"

if __name__ == "__main__":
    inp = raw_input()
    input = inp.rsplit(' ')
    n = int(input[0])
    m = int(input[1])
    arrprice = []
    inp = raw_input()
    input = inp.rsplit(' ')
    for i in range(0,n):
        arrprice.append(int(input[i]))

    arrpairs = [0] * n
    for i in range(n):
        arrpairs[i] = []

    for i in range(0,m):
        inp = raw_input()
        input = inp.rsplit(' ')
        x = int(input[0])
        y = int(input[1])
        arrpairs[x-1].append(y)
        arrpairs[y-1].append(x)

    minprice = -1
    price = ''
    first = 1

    ii = 0
    for i in arrpairs:
        for j in range(0,len(i)-1):
            for k in range(j+1,len(i)):
                if i[k] in arrpairs[i[j]-1]:
                    price = arrprice[ii] + arrprice[i[j]-1] + arrprice[i[k]-1]
                    if(first==1 or price<minprice):
                        first = 0
                        minprice = price
        ii+=1

    print minprice


#def gcd(a,b):
#   while b > 0: a,b = b, a%b
#   return a
#def lcm(a, b):
#   return a*b/gcd(a,b)

T, N = map(int, raw_input().split())
#S = raw_input()
fld = [[0]*T for i in xrange(T)]
data = map(int, raw_input().split())
data2 = [ map(int, raw_input().split()) for i in xrange(N)]
for i in data2:
    fld[i[0]-1][i[1]-1] = 1
    fld[i[1]-1][i[0]-1] = 1
cost = 2**99

for i in xrange(T):
    for j in xrange(T):
        for z in xrange(T):
            if i != j and j != z and z != i and fld[i][j] and fld[j][z] and fld[z][i]:
                cost = min(cost, sum([data[i], data[j], data[z]]))

if cost == 2**99:
    print -1
else:
    print cost


#def gcd(a,b):
#   while b > 0: a,b = b, a%b
#   return a
#def lcm(a, b):
#   return a*b/gcd(a,b)

T, N = map(int, raw_input().split())
#S = raw_input()

data = map(int, raw_input().split())
data2 = [ map(int, raw_input().split()) for i in xrange(N)]

cost = 2**99

for i in data2:
    for j in data2:
        for z in data2:
            if i != j and i != z and j != z:
                k = set(i+j+z)
                if len(k) == 3:
                    print i, j, z
                    cost = min(cost, sum([ data[p-1] for p in k]))

if cost == 2**99:
    print -1
else:
    print cost


#def gcd(a,b):
#   while b > 0: a,b = b, a%b
#   return a
#def lcm(a, b):
#   return a*b/gcd(a,b)

T, N = map(int, raw_input().split())
#S = raw_input()

data = map(int, raw_input().split())
data2 = [ set(map(int, raw_input().split())) for i in xrange(N)]

cost = 2**99

for i in data2:
    for j in data2:
        if len(i | j) == 3:
            if i^j in data2:
                cost = min(cost, sum([data[y-1] for y in (i | j)]))

if cost == 2**99:
    print -1
else:
    print cost


#def gcd(a,b):
#   while b > 0: a,b = b, a%b
#   return a
#def lcm(a, b):
#   return a*b/gcd(a,b)

T, N = map(int, raw_input().split())
#S = raw_input()

data = map(int, raw_input().split())
data2 = [ map(int, raw_input().split()) for i in xrange(N)]

cost = 2**99

for i in data2:
    for j in data2:
        for z in data2:
            if i != j and i != z and j != z:
                k = set(i+j+z)
                if len(k) == 3:
                    cost = min(cost, sum([ data[p-1] for p in k]))

if cost == 2**99:
    print -1
else:
    print cost


from itertools import *
from heapq import *
from string import *
from collections import deque

def get2d(a, b, elem = -1):
  res = []
  for x in range(a):
    res.append(list(repeat(elem, b)))
  return res

def getTuple():
  return tuple(getList())

def getList():
  return map(long, raw_input().split())

def getInt():
  return long(raw_input())

N, M = getTuple()
prices = getList()
data = {}

for i in xrange(M):
  a, b = getTuple()
  a -= 1
  b -= 1
  data[1000 * a + b] = True
  data[1000 * b + a] = True

B = 10000000000
best = B

#print prices
#print data

for tup in combinations(range(N), 3):
  #print tup
  if ((1000 * tup[0] + tup[1]) in data and
      (1000 * tup[2] + tup[1]) in data and
      (1000 * tup[0] + tup[2]) in data):
    best = min(best, prices[tup[0]] + prices[tup[1]] + prices[tup[2]])

print -1 if best == B else best


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
ma = [[False] * n for _ in range(n)]
for j in range(m):
    u, v = map(int, raw_input().split())
    ma[u - 1][v - 1] = True
    ma[v - 1][u - 1] = True

res = None
for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if ma[i][j] and ma[j][k] and ma[i][k]:
                s = a[i] + a[j] + a[k]
                if res is None or s < res:
                    res = s
print -1 if res is None else res


R = lambda: map(int, raw_input().split())
(n, m), a = R(), R()
matrix = [[0]*n for _ in range(n)]
for i in range(m):
	x, y = R()
	x, y = min(x,y)-1, max(x,y)-1
	matrix[x][y] = 1
min = -1
m = matrix
for i in range(n):
	for j in range(i+1,n):
		for k in range(j+1,n):
			if m[i][j] and m[j][k] and m[i][k]:
				c = a[i] + a[j] + a[k]
				if min < 0 or c < min:
					min = c
print min


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())

if M < 3:
    print str(-1)
else:
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    groups = []
    for m in range(len(I)):
        for first in I[m]:
            if first < m :
                continue
            else:
                for second in I[first] :
                    for third in I[second]:
                        if third == m:
                            groups.append(P[m]+P[first]+P[second])
    if len(groups) == 0 :
        print "-1"
    else:
        print str(min(groups))


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
P2 = sorted(P2,reverse=True)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(I[m]) < 2:continue
        for first in I[m]:
            if len(I[first]) < 2:continue
            for second in I[first] :
                if len(I[second]) < 2:continue
                if second != m:
                    if m in I[second]:
                        total = P[m]+P[first]+P[second]
                        if total < min_value :
                            min_value = total
                        if same or real_min == min_value:
                            is_break = True
                            break
            if  is_break: break
        if is_break: break

    if min_value == 999999999999999 :
        print "-1"
    else:
        print str(min_value)


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
for p in P:
    if p != last:
        same = False
        break
if M < 3:
    print str(-1)
else:
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    groups = []
    is_break = False
    for m in range(len(I)):
        for first in I[m]:
            for second in I[first] :
                if second != m:
                    if m in I[second]:
                        groups.append(P[m]+P[first]+P[second])
                        if same:
                            is_break = True
                            print "break"
                            break
            if same and is_break: break
        if same and is_break: break
    if len(groups) == 0 :
        print "-1"
    else:
        print str(min(groups))


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
P2 = sorted(P2)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(I[m]) < 2:continue
        for first in I[m]:
            if len(I[first]) < 2:continue
            for second in I[first] :
                if len(I[second]) < 2:continue
                if second != m:
                    if len(I[m]) > len(I[second]):
                        if m in I[second]:
                            total = P[m]+P[first]+P[second]
                            if total < min_value :
                                min_value = total
                            if same or real_min == min_value:
                                is_break = True
                                break
                    else:
                        if second in I[m]:
                            total = P[m]+P[first]+P[second]
                            if total < min_value :
                                min_value = total
                            if same or real_min == min_value:
                                is_break = True
                                break

            if  is_break: break
        if is_break: break

    if min_value == 999999999999999 :
        print "-1"
    else:
        print str(min_value)


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
for p in P:
    if p != last:
        same = False
        break
if M < 3:
    print str(-1)
else:
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    groups = []
    is_break = False
    for m in range(len(I)):
        for first in I[m]:
            for second in I[first] :
                if second != m:
                    if m in I[second]:
                        del I[m][first]
                        del I[first][m]
                        del I[first][second]
                        del I[second][first]
                        del I[second][m]
                        del I[m][second]
                        groups.append(P[m]+P[first]+P[second])
                        if same:
                            is_break = True
                            break
            if same and is_break: break
        if same and is_break: break
    if len(groups) == 0 :
        print "-1"
    else:
        print str(min(groups))


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
P2 = sorted(P2)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
#        I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(I[m]) < 2:continue
        for first in I[m]:
            if len(I[first]) < 2:continue
            for second in I[first] :
                if len(I[second]) < 2:continue
                if second != m:
#                 if len(I[m]) > len(I[second]):
                    if m in I[second]:
                        total = P[m]+P[first]+P[second]
                        if total < min_value :
                            min_value = total
                        if same or real_min == min_value:
                            is_break = True
                            break
#                    else:
#                        if second in I[m]:
#                            total = P[m]+P[first]+P[second]
#                            if total < min_value :
#                                min_value = total
#                            if same or real_min == min_value:
#                                is_break = True
#                                break
#
            if  is_break: break
        if is_break: break

    if min_value == 999999999999999 :
        print "-1"
    else:
        print str(min_value)


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
P2 = sorted(P2)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        if i < j :
            I[i-1].append(j-1)
        else:
            I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(I[m]) < 2:continue
        for first in I[m]:
            for second in I[first] :
                if second != m:
                    if len(I[m]) > len(I[second]):
                        if second in I[m]:
                            total = P[m]+P[first]+P[second]
                            if total < min_value :
                                min_value = total
                            if same or real_min == min_value:
                                is_break = True
                                break
            if  is_break: break
        if is_break: break

    if min_value == 999999999999999 :
        print "-1"
    else:
        print str(min_value)


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
        break
P2 = sorted(P2,reverse=True)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(m) < 2:continue
        for first in I[m]:
            if len(first) < 2:continue
            for second in I[first] :
                if len(second) < 2:continue
                if second != m:
                    if m in I[second]:
                        total = P[m]+P[first]+P[second]
                        if total < min_value :
                            min_value = total
                        if same or real_min == min_value:
                            is_break = True
                            break
            if  is_break: break
        if is_break: break

    if len(groups) == 0 :
        print "-1"
    else:
        print str(min_value)


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
for p in P:
    if p != last:
        same = False
        break
if M < 3:
    print str(-1)
else:
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    groups = []
    is_break = False
    for m in range(len(I)):
        for first in I[m]:
            for second in I[first] :
                if second != m:
                    if m in I[second]:
                        del I[m][I[m].index(first)]
                        del I[first][I[first].index(m)]
                        del I[first][I[first].index(second)]
                        del I[second][I[second].index(first)]
                        del I[second][I[second].index(m)]
                        del I[m][I[m].index(second)]
                        groups.append(P[m]+P[first]+P[second])
                        if same:
                            is_break = True
                            break
            if same and is_break: break
        if same and is_break: break
    if len(groups) == 0 :
        print "-1"
    else:
        print str(min(groups))


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())

if M < 3:
    print str(-1)
else:
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    groups = []
    for m in range(M):
        for first in I[m]:
            if first < m :
                continue
            else:
                for second in I[first] :
                    for third in I[second]:
                        if third == m:
                            groups.append(P[m]+P[first]+P[second])
    if len(groups) == 0 :
        print "-1"
    else:
        print str(min(groups))


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
P2 = sorted(P2)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(I[m]) < 2:continue
        for first in I[m]:
            if len(I[first]) < 2:continue
            for second in I[first] :
                if len(I[second]) < 2:continue
                if second != m:
                    if len(I[m]) > len(I[second]):
                        if m in I[second]:
                            total = P[m]+P[first]+P[second]
                            if total < min_value :
                                min_value = total
                            if same or real_min == min_value:
                                is_break = True
                                break
            if  is_break: break
        if is_break: break

    if min_value == 999999999999999 :
        print "-1"
    else:
        print str(min_value)


N,M = map(int,raw_input().split())
P = map(int,raw_input().split())
same = True
last = P[0]
min_value = 999999999999999
P2 = []
for p in P:
    P2.append(p)
    if p != last:
        same = False
P2 = sorted(P2)
if M < 3 or N < 3:
    print "-1"
else:
    real_min = P2[0] + P2[1] + P2[2]
    I = [[] for i in range(N)]
    for m in range(M):
        i,j = map(int,raw_input().split())
        I[i-1].append(j-1)
        I[j-1].append(i-1)
    is_break = False
    for m in range(len(I)):
        if len(I[m]) < 2:continue
        for first in I[m]:
            if len(I[first]) < 2:continue
            for second in I[first] :
                if len(I[second]) < 2:continue
                if second != m:
                    if m in I[second]:
                        total = P[m]+P[first]+P[second]
                        if total < min_value :
                            min_value = total
                        if same or real_min == min_value:
                            is_break = True
                            break
            if  is_break: break
        if is_break: break

    if min_value == 999999999999999 :
        print "-1"
    else:
        print str(min_value)


import sys

n,m = [int(_) for _ in raw_input().split()]
a = map(int, raw_input().split())
v=set()

for l in sys.stdin.readlines():
    _=tuple(int(q) - 1 for q in l.split())
    v.add(_)
    v.add(_[::-1])

m = 10**7
for i in xrange(len(a)):
    for j in xrange(len(a)):
        for k in xrange(len(a)):
            if (i,j) in v and (j,k) in v and (k,i) in v:
                if a[i] + a[j] + a[k] < m:
                    m = a[i] + a[j] + a[k]

if m == 10**7:
    print -1
else:
    print m


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools, collections

n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
dep = collections.defaultdict(set)
for _ in xrange(m):
    u, v = map(int, raw_input().split())
    dep[u-1].add(v-1)
    dep[v-1].add(u-1)
ans = 10**10
for x, y, z in itertools.combinations(range(n), 3):
    if y in dep[x] and z in dep[x] and y in dep[z]:
        ans = min(ans, a[x]+a[y]+a[z])
print -1 if ans == 10**10 else ans


r=lambda: map(int,raw_input().split())
n,m=r()
a=r()
rn=range(n)
l=[[0]*n for i in rn]
for i in range(m):
	v,u=r()
	v-=1
	u-=1
	l[u][v]=l[v][u]=1
mx=10**10
an=mx
for i in rn:
	for j in range(i+1,n):
		for k in range(j+1,n):
			if l[i][j] and l[j][k] and l[k][i]:
				an=min(an,a[i]+a[j]+a[k])
print -1 if an==mx else an


import sys
def read_values():
  return map(int,raw_input().split())
INF=10**9
n,m = read_values()
a = [[False]*n for i in range(n)]
values = read_values()
for i in range(m):
  u,v=read_values()
  u-=1
  v-=1
  a[u][v] = True
  a[v][u] = True
res=INF
for i in range(n):
  for j in range(n):
    for k in range(n):
      if a[i][j] and a[i][k] and a[j][k]:
        s = sum([values[ind] for ind in [i,j,k]])
        res = min(res,s)
if res==INF: res=-1
print res


ss = raw_input().split(' ')
n,m = int(ss[0]), int(ss[1])
a = [int(i) for i in raw_input().split(' ')]
g = []
for i in xrange(n): g.append([False] * n)
for _ in xrange(m):
    x,y = (int(i)-1 for i in raw_input().split(' '))
    g[x][y] = g[y][x] = True
r = 1 << 30
for i in xrange(n):
    for j in xrange(i):
        for k in xrange(j):
            if g[i][j] and g[j][k] and g[k][i]:
                r = min(r, a[i] + a[j] + a[k])
if r == (1 << 30):
    print -1
else:
    print r


#!/usr/bin/python

f = lambda : map(int , raw_input().split())
n , m = f()
price = f()

L = [[0] * n for i in xrange(n)]

for i in range(m):
	a , b =map(lambda x : x - 1, f())
	L[a][b] = L[b][a] = 1

Min = 1 << 30

for i in range(n):
	for j in range(i + 1 , n):
		for k in range(j + 1 , n):
			if L[i][j] == 1 and L[j][k] == 1 and L[k][i] == 1:
				Min = min(Min , price[i] + price[j] + price[k])

if Min == 1 << 30:
	print("-1")
else:
	print(Min)


#!/usr/bin/python

INF = 1000000000000000

L = {}

[n , m] = map(int, raw_input().split())

price = map(int , raw_input().split())

for i in range(n):
	L[i] = []

for i in range(m):
	[a , b] = map(int , raw_input().split())
	a -= 1
	b -= 1
	L[a].append(b)
	L[b].append(a)

Min = INF
for i in range(n):
	#print(L[i])
	for j in L[i]:
		for k in L[j]:
			if k in L[i]:
				Min = min(Min , price[i] + price[j] + price[k])

if Min == INF:
	print("-1")
else:
	print(Min)


from itertools import *

line = raw_input()
y = line.find(' ')
n = int(line[:y])
line = line[y+1:]
m = int(line)

line = raw_input()
price = []

for i in range(0,n-1):
    y = line.find(' ')
    prc = line[:y]
    x = int(prc)
    price.append(x)
    line = line[y+1:]
price.append(int(line))

tbl = []

for i in range(0,n):
    tbl.append([])
    tbl[i].append(i)

for i in range(0,m):
    line = raw_input()
    z = line.find(' ')
    x = int(line[:z])
    line = line[z+1:]
    y = int(line)
    tbl[x-1].append(y-1)
    tbl[y-1].append(x-1)

val = 4 * 10**6
cmb = list(combinations(range(0,n),3))
for i in cmb:
    if i[0] in tbl[i[1]] and i[0] in tbl[i[2]] and \
       i[1] in tbl[i[0]] and i[1] in tbl[i[2]] and \
       i[2] in tbl[i[0]] and i[2] in tbl[i[1]]:
        mon = price[i[0]] + price[i[1]] + price[i[2]]
        if mon<val:
            val = mon
if val == 4 * 10**6:
    print -1
else:
    print val


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))
import pdb

pair = [[False for i in range(n)] for j in range(n)]

for _ in range(m):
    k, l = map(int, raw_input().split(' '))
    k -= 1
    l -= 1
    #pdb.set_trace()
    pair[k][l] = True
    pair[l][k] = True

le = len(pair)
mx = 10**9

def per():
    s = mx
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(j + 1, le):
                    if (pair[i][j] & pair[j][k] & pair[k][i]):
                        s = min(s,sum[i]+sum[j]+sum[k])

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m
for i in range(m):
    pair[i] = map(int, raw_input().split(' '))
le = len(pair)

def per():
    s = []
    for i in range(le):
        for j in range(i + 1, le):
            if (pair[i][0] == pair[j][0]):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) & (pair[k][1] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1])))
                    if ((pair[j][1] == pair[k][1]) & (pair[k][0] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1])))
            if (pair[i][0] == pair[j][1]):
                for k in range(i + 1, le):
                    if ((pair[j][0] == pair[k][0]) & (pair[k][1] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][0] - 1])))
                    if ((pair[j][0] == pair[k][1]) & (pair[k][0] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][0] - 1])))
    return s

s = per()
if s:
    print min(s)
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))
import pdb

pair = [[False for i in range(m)] for j in range(m)]

for _ in range(m):
    k, l = map(int, raw_input().split(' '))
    k -= 1
    l -= 1
    #pdb.set_trace()
    pair[k][l] = True
    pair[l][k] = True

le = len(pair)
mx = 10**9

def per():
    s = mx
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(j + 1, le):
                    if (pair[i][j] & pair[j][k] & pair[k][i]):
                        s = min(s,sum[i]+sum[j]+sum[k])

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m
for i in range(m):
    pair[i] = map(int, raw_input().split(' '))
le = len(pair)

def per():
    s = []
    for i in range(le):
        for j in range(i + 1, le):
            if (pair[i][0] == pair[j][0]):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) & (pair[k][1] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1])))
                    if ((pair[j][1] == pair[k][1]) & (pair[k][0] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1])))
            if (pair[i][0] == pair[j][1]):
                for k in range(i + 1, le):
                    if ((pair[j][0] == pair[k][0]) & (pair[k][1] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][0] - 1])))
                    if ((pair[j][0] == pair[k][1]) & (pair[k][0] == pair[i][1]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][0] - 1])))
    return s

s = per()
if s:
    print min(s)


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m*2
for i in range(0, 2*m, 2):
    pair[i] = map(int, raw_input().split(' '))
    pair[i + 1] = [0, 0]
    pair[i + 1][0] = pair[i][1]
    pair[i + 1][1] = pair[i][0]
le = len(pair)
mx = 10**9

def per():
    s = mx
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(j + 1, le):
                    a = pair[j][1]
                    b = pair[k][0]
                    c = pair[k][1]
                    d = pair[i][1]
                    e = pair[i][0]
                    f = pair[j][0]
                    if ((a == b) &
                        (c == d) &
                        (e == f) &
                        (j != k)):
                        s = min(s,(int(sum[e - 1])+
                                    int(sum[d - 1])+
                                    int(sum[a - 1])))

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m*2
for i in range(0, 2*m, 2):
    pair[i] = map(int, raw_input().split(' '))
    pair[i + 1] = [0, 0]
    pair[i + 1][0] = pair[i][1]
    pair[i + 1][1] = pair[i][0]
le = len(pair)
mx = 10**9
def per():
    s = mx
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) &
                        (pair[k][1] == pair[i][1]) &
                        (pair[i][0] == pair[j][0]) &
                        (j != k)):
                        s = min(mx,(int(sum[pair[i][0] - 1])+
                                    int(sum[pair[i][1] - 1])+
                                    int(sum[pair[j][1] - 1])))

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m*2
for i in range(0, 2*m, 2):
    pair[i] = map(int, raw_input().split(' '))
    pair[i + 1] = [0, 0]
    pair[i + 1][0] = pair[i][1]
    pair[i + 1][1] = pair[i][0]
le = len(pair)

def per():
    s = []
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) &
                        (pair[k][1] == pair[i][1]) &
                        (pair[i][0] == pair[j][0]) &
                        (j != k)):
                        s.append((int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1])))

    return s

s = per()
if s:
    print min(s)
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m*2
for i in range(0, 2*m, 2):
    pair[i] = map(int, raw_input().split(' '))
    pair[i + 1] = [0, 0]
    pair[i + 1][0] = pair[i][1]
    pair[i + 1][1] = pair[i][0]
le = len(pair)
mx = 10**9

def per():
    s = mx
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(j + 1, le):
                    if ((pair[j][1] == pair[k][0]) &
                        (pair[k][1] == pair[i][1]) &
                        (pair[i][0] == pair[j][0]) &
                        (j != k)):
                        s = min(s,(int(sum[pair[i][0] - 1])+
                                    int(sum[pair[i][1] - 1])+
                                    int(sum[pair[j][1] - 1])))

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m*2
for i in range(0, 2*m, 2):
    pair[i] = map(int, raw_input().split(' '))
    pair[i + 1] = [0, 0]
    pair[i + 1][0] = pair[i][1]
    pair[i + 1][1] = pair[i][0]
le = len(pair)
mx = 10**9
def per():
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) &
                        (pair[k][1] == pair[i][1]) &
                        (pair[i][0] == pair[j][0]) &
                        (j != k)):
                        s = min(mx,(int(sum[pair[i][0] - 1])+
                                    int(sum[pair[i][1] - 1])+
                                    int(sum[pair[j][1] - 1])))

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m*2
for i in range(0, 2*m, 2):
    pair[i] = map(int, raw_input().split(' '))
    pair[i + 1] = [0, 0]
    pair[i + 1][0] = pair[i][1]
    pair[i + 1][1] = pair[i][0]
le = len(pair)
mx = 10**9
def per():
    s = mx
    for i in range(le):
        for j in range(i + 1, le):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) &
                        (pair[k][1] == pair[i][1]) &
                        (pair[i][0] == pair[j][0]) &
                        (j != k)):
                        s = min(s,(int(sum[pair[i][0] - 1])+
                                    int(sum[pair[i][1] - 1])+
                                    int(sum[pair[j][1] - 1])))

    return s

s = per()
if s != mx:
    print s
else:
    print -1


n,m = map(int, raw_input().split(' '))
sum = map(int, raw_input().split(' '))

pair = [0]*m
for i in range(m):
    pair[i] = map(int, raw_input().split(' '))
le = len(pair)

def per():
    tmp = 0
    for i in range(le):
        for j in range(i + 1, le):
            if (pair[i][0] == pair[j][0]):
                for k in range(i + 1, le):
                    if ((pair[j][1] == pair[k][0]) & (pair[k][1] == pair[i][1]) &
                        (j != k)):
                        return (int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1]))
                    if ((pair[j][1] == pair[k][1]) & (pair[k][0] == pair[i][1]) &
                        (j != k)):
                        return (int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][1] - 1]))
            if (pair[i][0] == pair[j][1]):
                for k in range(i + 1, le):
                    if ((pair[j][0] == pair[k][0]) & (pair[k][1] == pair[i][1]) &
                        (j != k)):
                        return (int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][0] - 1]))
                    if ((pair[j][0] == pair[k][1]) & (pair[k][0] == pair[i][1]) &
                        (j != k)):
                        return (int(sum[pair[i][0] - 1])+
                                int(sum[pair[i][1] - 1])+
                                int(sum[pair[j][0] - 1]))
    return -1

print per()


import sys

INF = float('inf')

n, m = map(int, sys.stdin.readline().split())

p = map(int, sys.stdin.readline().split())

match = [[False for i in xrange(n)] for i in xrange(n)]

for i in xrange(m):
    a, b = map(int, sys.stdin.readline().split())
    match[a-1][b-1] = True
    match[b-1][a-1] = True

ret = INF
for i in xrange(n):
    for j in xrange(i, n):
        for k in xrange(j, n):
            if match[i][j] and match[j][k] and match[k][i]:
                ret = min(ret, p[i]+p[j]+p[k])

if ret == INF:
    print "-1"
else:
    print ret


import sys

n,m = [int(_) for _ in raw_input().split()]
a = map(int, raw_input().split())
v=set()

for l in sys.stdin.readlines():
    _=tuple(int(q) - 1 for q in l.split())
    v.add(_)
    v.add(_[::-1])

m = 10**7
for i in xrange(len(a)):
    for j in xrange(len(a)):
        for k in xrange(len(a)):
            if (i,j) in v and (j,k) in v and (k,i) in v:
                if a[i] + a[j] + a[k] < m:
                    m = a[i] + a[j] + a[k]

if m == 10**7:
    print -1
else:
    print m


from sys import stdin

n, m = map(int, stdin.readline().split(' '))
p = map(int, stdin.readline().split(' '))

best = 10**10
s = set([tuple(map(lambda s: int(s)-1, stdin.readline().split(' '))) for i in range(m)])

for i in range(n):
    for j in range(n):
        if (i,j) in s:
            for k in range(n):
                if (j,k) in s and (i,k) in s:
                    best = min(best, p[i]+p[j]+p[k])

print -1 if best == 10**10 else best


from sys import stdin

n, m = map(int, stdin.readline().split(' '))
p = map(int, stdin.readline().split(' '))

best = 10**10
s = set([tuple(map(lambda s: int(s)-1, stdin.readline().split(' '))) for i in range(m)])
s |= set([(v,u) for (u,v) in s])

for i in range(n):
    for j in range(n):
        if (i,j) in s:
            for k in range(n):
                if (j,k) in s and (i,k) in s:
                    best = min(best, p[i]+p[j]+p[k])

print -1 if best == 10**10 else best


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int n,m,a[1000],b[1000],price;
	int clo[105][105]={0},x,y;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		b[i-1]=a[i];
	}
	sort(b,b+n);
	price=4*b[n-1]+1;

	for(int i=0;i<m;i++)
	{
		cin>>x>>y;
		clo[y][x]=clo[x][y]=1;
	}
	int num_p=0;
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(j!=i)
			{
				for(int k=1;k<=m;k++)
				{
					if(k!=i&&k!=j)
					{
						if(clo[i][k]==1&&clo[i][j]==1&&clo[j][k]==1)
						{
							num_p=a[i]+a[k]+a[j];
							if(num_p<price)
							{
								price=num_p;
							}

						}
					}
				}
			}
		}
	}
	if(num_p==0) cout<<"-1"<<endl;
	else cout<<price<<endl;
	return 0;
}


#include <stdio.h>

int cloth[101][101], price[101];

int main()

{

int n, m, i, j, k, x, y, cost, min;

while(scanf("%d%d", &n, &m)!=EOF)

{

cost=0; min=0xffffff;

for(i=1; i<=n; i++)

scanf("%d", &price[i]);

for(i=0; i<m; i++)

{

scanf("%d%d", &x, &y);

cloth[x][y]=cloth[y][x]=1;

}

for(i=1; i<=n; i++)

{

for(j=1; j<=n; j++)

{

if(i!=j)

{

for(k=1; k<=n; k++)

{

if(i!=k&&k!=j)

{

if(cloth[i][j]==1&&cloth[j][k]==1&&cloth[k][i]==1)

{

cost=price[i]+price[j]+price[k];

if(cost<min)

min=cost;

}

}

}

}

}

}

if(min==0xffffff)

printf("-1\n");

else

printf("%d\n", min);

}

return 0;
}


#include <stdio.h>

int cloth[101][101], price[101];

int main()

{

int n, m, i, j, k, x, y, cost, min;

while(scanf("%d%d", &n, &m)!=EOF)

{

cost=0; min=0xffffff;

for(i=1; i<=n; i++)

scanf("%d", &price[i]);

for(i=0; i<m; i++)

{

scanf("%d%d", &x, &y);

cloth[x][y]=cloth[y][x]=1;

}

for(i=1; i<=n; i++)

{

for(j=1; j<=n; j++)

{

if(i!=j)

{

for(k=1; k<=n; k++)

{

if(i!=k&&k!=j)

{

if(cloth[i][j]&&cloth[j][k]==1&&cloth[k][i]==1)

{

cost=price[i]+price[j]+price[k];

if(cost<min)

min=cost;

}

}

}

}

}

}

if(min==0xffffff)

printf("-1\n");

else

printf("%d\n", min);

}

return 0;
}


#include <stdio.h>

int cloth[101][101], price[101];

int main()

{

int n, m, i, j, k, x, y, cost, min;

scanf("%d%d", &n, &m);

{

cost=0; min=0xffffff;

for(i=1; i<=n; i++)

scanf("%d", &price[i]);

for(i=0; i<m; i++)

{

scanf("%d%d", &x, &y);

cloth[x][y]=cloth[y][x]=1;

}

for(i=1; i<=n; i++)

{

for(j=1; j<=n; j++)

{

if(i!=j)

{

for(k=1; k<=n; k++)

{

if(i!=k&&k!=j)

{

if(cloth[i][j]==1&&cloth[j][k]==1&&cloth[k][i]==1)

{

cost=price[i]+price[j]+price[k];

if(cost<min)

min=cost;

}

}

}

}

}

}

if(min==0xffffff)

printf("-1\n");

else

printf("%d\n", min);

}

return 0;
}


#include <stdio.h>

int cloth[101][101], price[101];

int main()

{

int n, m, i, j, k, x, y, cost, min;

while(scanf("%d%d", &n, &m)!=EOF)

{

cost=0; min=0xffffff;

for(i=1; i<=n; i++)

scanf("%d", &price[i]);

for(i=0; i<m; i++)

{

scanf("%d%d", &x, &y);

cloth[x][y]=cloth[y][x]=1;

}

for(i=1; i<=n; i++)

{

for(j=1; j<=n; j++)

{

if(i!=j)

{

for(k=1; k<=n; k++)

{

if(i!=k&&k!=j)

{

if(cloth[i][j]&&cloth[j][k]==1&&cloth[k][i]==1)

{

cost=price[i]+price[j]+price[k];

if(cost<min)

min=cost;

}

}

}

}

}

}

if(min==0xffffff)

printf("-1\n");

else

printf("%d\n", min);

}

return 0;


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

namespace Codeforces
{
    class Task
    {
        static void Main()
        {
            long res = long.MaxValue;

            var input = Console.ReadLine().Split(' ');
            var n = Int32.Parse(input[0]);
            var m = Int32.Parse(input[1]);

            input = Console.ReadLine().Split(' ');
            var cost = new int[input.Length];
            for(int i = 0; i < input.Length; i++)
            {
                cost[i] = Int32.Parse(input[i]);
            }

            var pairs = new Dictionary<int, List<int>>();
            for (int i = 0; i < m; i++)
            {
                input = Console.ReadLine().Split(' ');
                int a = Int32.Parse(input[0]);
                int b = Int32.Parse(input[1]);
                if(!pairs.Keys.Contains(a))
                    pairs.Add(a, new List<int>());
                pairs[a].Add(b);
                if(!pairs.Keys.Contains(b))
                    pairs.Add(b, new List<int>());
                pairs[b].Add(a);
            }

            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 (!pairs.ContainsKey(i + 1) || !pairs.ContainsKey(j + 1) || !pairs.ContainsKey(k + 1))
                            continue;
                        if (pairs[i + 1].Contains(j + 1) && pairs[i + 1].Contains(k + 1) && pairs[j+1].Contains(k+1))
                            res = Math.Min(res, cost[i] + cost[j] + cost[k]);
                    }
                }
            }
            if(res == long.MaxValue)
                Console.WriteLine(-1);
            else
                Console.WriteLine(res);
        }
    }
}


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

namespace codeforces79A
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] str = Console.ReadLine().Split(' ');
            int n = int.Parse(str[0]);
            int m = int.Parse(str[1]);
            str = Console.ReadLine().Split(' ');
            int[] prices = new int[n];
            for (int i = 0; i < n; i++) prices[i] = int.Parse(str[i]);
            int[,] a = new int[n, n];
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    a[i, j] = 0;
            for (int i = 0; i < m; i++)
            {
                str = Console.ReadLine().Split(' ');
                a[int.Parse(str[0])-1, int.Parse(str[1])-1] = 1;
                a[int.Parse(str[1])-1, int.Parse(str[0])-1] = 1;
            }
            int min = Int32.MaxValue;
            for (int i=0; i<n; i++)
                for (int j=0; j<n; j++)
                    if (i!=j)
                        for (int k=0; k<n; k++)
                            if (k != i && k != j)
                            {
                                if (a[i, j] == 1 && a[k, i] == 1 && a[j, k] == 1 && prices[i] + prices[j] + prices[k] < min)
                                    min = prices[i] + prices[j] + prices[k];
                            }
            if (min==Int32.MaxValue)
                Console.Write(-1);
            else
            Console.Write(min);
        }
    }
}


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

namespace Crypt
{
    class Program
    {
        public static void Main()
        {
            int minCost = int.MaxValue;
            string[] str = Console.ReadLine().Split(' ');
            int n = int.Parse(str[0]);
            int m = int.Parse(str[1]);
            int[] cost = new int[n];
            int[,] pair = new int[m, 2];
            str = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
                cost[i] = int.Parse(str[i]);

            for (int i = 0; i < m; i++)
            {
                str = Console.ReadLine().Split(' ');
                pair[i, 0] = int.Parse(str[0]);
                pair[i, 1] = int.Parse(str[1]);
            }
            if (m < 3) { Console.WriteLine(-1); return; }

            for (int i = 0; i < m; i++)
            {
                 int[] set = new int[3];
                 set[0] = pair[i, 0];
                 set[1] = pair[i, 1];
                for (int j = 0; j < m; j++)
                {
                    if (i == j) continue;
                    set[2] = -1;
                    if (pair[j, 0] != set[0] && pair[j, 0] != set[1])
                    {
                        set[2] = pair[j, 0];
                    }
                    if (set[2] == -1 && pair[j, 1] != set[1] && pair[j, 1] != set[0])
                    {
                        set[2] = pair[j, 1];
                    }
                    if (pair[i, 0] == pair[j, 0] || pair[i, 0] == pair[j, 1] || pair[i, 1] == pair[j, 1] || pair[i, 1] == pair[j, 0])
                    {
                        for (int k = 0; k < m; k++)
                        {
                            if (k == i || k == j) continue;
                            if((pair[k,0]==set[0]||pair[k,0]==set[1]||pair[k,0]==set[2])&&(pair[k,1]==set[0]||pair[k,1]==set[1]||pair[k,1]==set[2]))
                            {
                                int nCost = pair[i, 0] + pair[i, 1] + ((pair[k, 0] != pair[i, 0] && pair[k, 0] != pair[i, 1]) ? pair[k, 0] : pair[k, 1]);
                                if (minCost > nCost)
                                    minCost = nCost;
                            }
                        }

                    }

                }
            }
            Console.WriteLine(minCost != int.MaxValue ? minCost : -1);

        }

    }
}


using System;
using System.Collections.Generic;
namespace Crypt
{
    class Program
    {
        public static void Main()
        {
            string[] str = Console.ReadLine().Split(' ');
            int n = int.Parse(str[0]);
            int m = int.Parse(str[1]);
            int[] price = new int[m];
            str = Console.ReadLine().Split(' ');
            for (int i = 0; i < m; i++)
            {
                price[i] = int.Parse(str[i]);
            }
            string[] matches = new string[m];
            for (int i = 0; i < m; i++)
            {
                matches[i] = Console.ReadLine();
            }
            Array.Sort(matches);
            long minCost = long.MaxValue;
            for (int i = 0; i < m; i++)
            {
                string[] sel1 = matches[i].Split(' ');
                for (int j = 0; j < m; j++)
                {
                    string[] sel2 = matches[j].Split(' ');
                    if (sel2[0] == sel1[1] && i != 0)
                    {
                        for (int k = 0; k < m; k++)
                        {
                            if (k == i || k == j) continue;
                            string[] sel3 = matches[k].Split(' ');
                            if (sel3[0] == sel2[1] && sel3[1] == sel1[0])
                            {
                                if (minCost > (long)price[i] + (long)price[j] + (long)price[k])
                                {

                                    minCost = (long)price[i] + (long)price[j] + (long)price[k];
                                }

                            }
                        }
                    }

                }
            }

            Console.WriteLine( minCost == long.MaxValue ? -1 : minCost);
        }
    }
}


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

namespace Crypt
{
    class Program
    {
        public static void Main()
        {
            int minCost = int.MaxValue;
            string[] str = Console.ReadLine().Split(' ');
            int n = int.Parse(str[0]);
            int m = int.Parse(str[1]);
            int[] cost = new int[n];
            int[,] pair = new int[m, 2];
            str = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
                cost[i] = int.Parse(str[i]);

            for (int i = 0; i < m; i++)
            {
                str = Console.ReadLine().Split(' ');
                pair[i, 0] = int.Parse(str[0]);
                pair[i, 1] = int.Parse(str[1]);
            }
            if (m < 3) { Console.WriteLine(-1); return; }

            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (i == j) continue;
                    if (pair[i, 0] == pair[j, 0] || pair[i, 0] == pair[j, 1] || pair[i, 1] == pair[j, 1] || pair[i, 1] == pair[j, 0])
                    {
                        for (int k = 0; k < m; k++)
                        {
                            if (k == i || k == j) continue;
                            if ((pair[i, 0] == pair[k, 0] || pair[i, 0] == pair[k, 1] || pair[i, 1] == pair[k, 1] || pair[i, 1] == pair[k, 0]) && (pair[j, 0] == pair[k, 0] || pair[j, 0] == pair[k, 1] || pair[j, 1] == pair[k, 1] || pair[j, 1] == pair[k, 0]))
                            {
                                int nCost = pair[i, 0] + pair[i, 1] + ((pair[k, 0] != pair[i, 0] && pair[k, 0] != pair[i, 1]) ? pair[k, 0] : pair[k, 1]);
                                if (minCost > nCost)
                                    minCost = nCost;
                            }
                        }

                    }

                }
            }
            Console.WriteLine(minCost != int.MaxValue ? minCost : -1);

        }

    }
}


using System;
using System.Collections.Generic;
namespace Crypt
{
    class Program
    {
        public static void Main()
        {
            string[] str = Console.ReadLine().Split(' ');
            int n = int.Parse(str[0]);
            int m = int.Parse(str[1]);
            int[] price = new int[n];
            str = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
            {
                price[i] = int.Parse(str[i]);
            }
            string[] matches = new string[m];
            for (int i = 0; i < m; i++)
            {
                matches[i] = Console.ReadLine();
            }
            Array.Sort(matches);
            //bool bln = isMatch2(matches[0].Split(' '), matches[1].Split(' '), matches[3].Split(' '));
            long minCost = long.MaxValue;
            for (int i = 0; i < m; i++)
            {
                string[] sel1 = matches[i].Split(' ');
                for (int j = 0; j < m; j++)
                {
                    string[] sel2 = matches[j].Split(' ');
                    if (isMatch(sel1,sel2) && i != 0)
                    {
                        for (int k = 0; k < m; k++)
                        {
                            if (k == i || k == j) continue;
                            string[] sel3 = matches[k].Split(' ');
                            int[] getMatch = isMatch2(sel1,sel2,sel3);
                            if (getMatch != null)
                            {
                                if (minCost > (long)price[getMatch[0]-1] + (long)price[getMatch[1]-1] + (long)price[getMatch[2]-1])
                                    minCost = (long)price[getMatch[0] - 1] + (long)price[getMatch[1] - 1] + (long)price[getMatch[2] - 1];

                            }
                        }
                    }

                }
            }

            Console.WriteLine( minCost == long.MaxValue ? -1 : minCost);
        }
        public static bool isMatch(string[] str1, string[] str2) {
            for (int i = 0; i < 2; i++) {
                if (str1[i] == str2[0] || str1[i] == str2[1])
                    return true;
            }
            return false;
        }
        public static int[] isMatch2(string[] str1, string[] str2, string[] str3) {
            List<string> strSum =new List<string>();//  {str1[0],str1[1],str2[0],str2[1]};
            strSum.Add(str1[0]);strSum.Add(str1[1]);strSum.Add(str2[0]);strSum.Add(str2[1]);
            strSum.Sort();
            for (int i = 1; i < strSum.Count; i++) {
                if (strSum[i] == strSum[i - 1])
                {
                    strSum.RemoveAt(i);
                    i--;
                }
            }
            int count=0;
            for (int i = 0; i < strSum.Count; i++) {
                if (strSum[i] == str3[0] || strSum[i] == str3[1])
                    count++;
            }
            if (count == 2) {
                int[] ret = new int[strSum.Count];
                for (int i = 0; i < strSum.Count; i++)
                    ret[i] = int.Parse(strSum[i]);
                return ret;
            }
            return null;

        }
    }
}


import sys
large = 1000000
def solve():
    s = input()
    t = input()
    if len(s) != len(t):
        print(-1)
        return
    n = int(input())
    mem = [[large] * 26 for _ in range(26)]
    for i in range(26):
        mem[i][i] = 0
    for i in range(n):
        chra, chrb, strcost = input().split()
        a = ord(chra) - ord('a')
        b = ord(chrb) - ord('a')
        cost = int(strcost)
        mem[a][b] = min(mem[a][b], cost)
        for start in range(26):
            for end in range(26):
                mem[start][end] = min(mem[start][end], mem[start][a] + mem[a][b] + mem[b][end])
    cost = 0
    res = [None] * len(s)
    for i in range(len(s)):
        mid = -1
        midcost = large
        a = ord(s[i]) - ord('a')
        b = ord(t[i]) - ord('a')
        for j in range(26):
            if mem[a][j] != -1 and mem[b][j] != -1:
                thiscost = mem[a][j] + mem[b][j]
                if thiscost < midcost:
                    midcost = thiscost
                    mid = j
        res[i] = chr(ord('a') + mid)
        cost += midcost
    if cost >= large:
        print(-1)
        return
    print(cost)
    print(''.join(map(str, res)))

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()


import sys
large = 10000000
def solve():
    s = input()
    t = input()
    if len(s) != len(t):
        print(-1)
        return
    n = int(input())
    mem = [[large] * 26 for _ in range(26)]
    for i in range(26):
        mem[i][i] = 0
    for i in range(n):
        chra, chrb, strcost = input().split()
        a = ord(chra) - ord('a')
        b = ord(chrb) - ord('a')
        cost = int(strcost)
        mem[a][b] = min(mem[a][b], cost)
        for start in range(26):
            for end in range(26):
                mem[start][end] = min(mem[start][end], mem[start][a] + mem[a][b] + mem[b][end])
    cost = 0
    res = [None] * len(s)
    for i in range(len(s)):
        mid = -1
        midcost = large
        a = ord(s[i]) - ord('a')
        b = ord(t[i]) - ord('a')
        for j in range(26):
            if mem[a][j] != -1 and mem[b][j] != -1:
                thiscost = mem[a][j] + mem[b][j]
                if thiscost < midcost:
                    midcost = thiscost
                    mid = j
        res[i] = chr(ord('a') + mid)
        cost += midcost
    if cost >= large:
        print(-1)
        return
    print(cost)
    print(''.join(map(str, res)))

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()


import java.io.*;
import java.util.*;

public class test {
    int INF = (int)1e9;
    long MOD = 1000000007;

    int n, m, c, r;
    int[] a;
    boolean[] vis;

    int go(int v) {
        if(v >= m) return 0;
        if(vis[v]) return 0;
        vis[v] = true;
        int l = v * 2, r = l + 1;
        int max = 0;
        if(l<m) max = a[l] + go(l);
        if(r<m) max = Math.max(max, a[r] + go(r));
        return max;
    }

    int f(int v, int ac) {
        if(v >= m) {
            return r - ac;
        }
        if(vis[v]) return 0;
        vis[v] = true;
        ac += a[v];
        int l = v * 2, r = l + 1;
        int x = f(l, ac);
        int y = f(r, ac);
        int min = Math.min(x, y);
        c += x + y - 2 * min;
        return min;
    }

    void solve(InputReader in, PrintWriter out) throws IOException {
        n = in.nextInt();
        m = (int)Math.pow(2, n+1);
        a = new int[m+10];
        int s = 0;
        for(int i=2; i<=m-1; i++) {
            a[i] = in.nextInt();
            s += a[i];
        }
        vis = new boolean[m+10];
        r = Math.max(a[2] + go(2), a[3] + go(3));
        c = 0;
        vis = new boolean[m+10];
        int x = f(1, 0);
        out.println(c + x);
    }

    public static void main(String[] args) throws IOException {
        if(args.length>0 && args[0].equalsIgnoreCase("d")) {
            DEBUG_FLAG = true;
        }
        InputReader in = new InputReader();
        PrintWriter out = new PrintWriter(System.out);
        int t = 1;//in.nextInt();
        long start = System.nanoTime();
        while(t-- >0) {
            new test().solve(in, out);
        }
        long end = System.nanoTime();
        debug("\nTime: " + (end-start)/1e6 + " \n\n");
        out.close();
    }

    static boolean DEBUG_FLAG = false;
    static void debug(String s) {
        if(DEBUG_FLAG) System.out.print(s);
    }

    static class InputReader {
        static BufferedReader br;
        static StringTokenizer st;

        public InputReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}


import java.io.*;
import java.util.*;

public class test {
    int INF = (int)1e9;
    long MOD = 1000000007;

    int n, m, c, r;
    int[] a;
    boolean[] vis;

    int go(int v) {
        if(v >= m) return 0;
        if(vis[v]) return 0;
        System.out.println(v);
        vis[v] = true;
        int l = v * 2, r = l + 1;
        int max = Math.max(a[l] + go(l), a[r] + go(r));
        return max;
    }

    int f(int v, int ac) {
        if(v >= m) {
            return r - ac;
        }
        if(vis[v]) return 0;
        vis[v] = true;
        ac += a[v];
        int l = v * 2, r = l + 1;
        int x = f(l, ac);
        int y = f(r, ac);
        int min = Math.min(x, y);
        c += x + y - 2 * min;
        return min;
    }

    void solve(InputReader in, PrintWriter out) throws IOException {
        n = in.nextInt();
        m = (int)Math.pow(2, n+1);
        a = new int[m+10];
        int s = 0;
        for(int i=2; i<=m-1; i++) {
            a[i] = in.nextInt();
            s += a[i];
        }
        vis = new boolean[m+10];
        r = Math.max(a[2] + go(2), a[3] + go(3));
        c = 0;
        vis = new boolean[m+10];
        int x = f(1, 0);
        out.println(c + x);
    }

    public static void main(String[] args) throws IOException {
        if(args.length>0 && args[0].equalsIgnoreCase("d")) {
            DEBUG_FLAG = true;
        }
        InputReader in = new InputReader();
        PrintWriter out = new PrintWriter(System.out);
        int t = 1;//in.nextInt();
        long start = System.nanoTime();
        while(t-- >0) {
            new test().solve(in, out);
        }
        long end = System.nanoTime();
        debug("\nTime: " + (end-start)/1e6 + " \n\n");
        out.close();
    }

    static boolean DEBUG_FLAG = false;
    static void debug(String s) {
        if(DEBUG_FLAG) System.out.print(s);
    }

    static class InputReader {
        static BufferedReader br;
        static StringTokenizer st;

        public InputReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}


import java.io.*;
import java.util.*;

public class test {
    int INF = (int)1e9;
    long MOD = 1000000007;

    int n, m, c, r;
    int[] a;
    boolean[] vis;

    int go(int v) {
        if(v >= m) return 0;
        if(vis[v]) return 0;
        vis[v] = true;
        int l = v * 2, r = l + 1;
        int max = Math.max(a[l] + go(l), a[r] + go(r));
        return max;
    }

    int f(int v, int ac) {
        if(v >= m) {
            return r - ac;
        }
        if(vis[v]) return 0;
        vis[v] = true;
        ac += a[v];
        int l = v * 2, r = l + 1;
        int x = f(l, ac);
        int y = f(r, ac);
        int min = Math.min(x, y);
        c += x + y - 2 * min;
        return min;
    }

    void solve(InputReader in, PrintWriter out) throws IOException {
        n = in.nextInt();
        m = (int)Math.pow(2, n+1);
        a = new int[m+10];
        int s = 0;
        for(int i=2; i<=m-1; i++) {
            a[i] = in.nextInt();
            s += a[i];
        }
        vis = new boolean[m+10];
        r = Math.max(a[2] + go(2), a[3] + go(3));
        c = 0;
        vis = new boolean[m+10];
        int x = f(1, 0);
        out.println(c + x);
    }

    public static void main(String[] args) throws IOException {
        if(args.length>0 && args[0].equalsIgnoreCase("d")) {
            DEBUG_FLAG = true;
        }
        InputReader in = new InputReader();
        PrintWriter out = new PrintWriter(System.out);
        int t = 1;//in.nextInt();
        long start = System.nanoTime();
        while(t-- >0) {
            new test().solve(in, out);
        }
        long end = System.nanoTime();
        debug("\nTime: " + (end-start)/1e6 + " \n\n");
        out.close();
    }

    static boolean DEBUG_FLAG = false;
    static void debug(String s) {
        if(DEBUG_FLAG) System.out.print(s);
    }

    static class InputReader {
        static BufferedReader br;
        static StringTokenizer st;

        public InputReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}


import java.util.*;

public class OmNomAndDankPank {
  private static class TreeNode {
    public TreeNode left;
    public TreeNode right;
    public int val;

    public TreeNode(int val) {
      this.val = val;
    }

    public String preorder() {
      StringBuilder s = new StringBuilder();
      s.append(val + ",");

      if (left != null) {
        s.append(left.preorder());
      }
      if (right != null) {
        s.append(right.preorder());
      }

      return s.toString();
    }
  }

  private static int totalToAdd;

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    TreeNode root = constructTree(n, in);
    //System.out.println(root.preorder());

    calc(root);
    System.out.println(totalToAdd);
  }

  // Returns the length of each path in root.
  private static int calc(TreeNode root) {
    if (root.left == null && root.right == null) {
      return 0;
    }

    int leftLength = calc(root.left) + root.left.val;
    int rightLength = calc(root.right) + root.right.val;

    totalToAdd += Math.abs(leftLength - rightLength);
    return Math.max(leftLength, rightLength);
  }

  private static TreeNode constructTree(int n, Scanner in) {
    TreeNode root = new TreeNode(0);
    Queue<TreeNode> q = new LinkedList<TreeNode>();
    q.add(root);
    int numNodes = 1;

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < numNodes; j++) {
        TreeNode curr = q.remove();
        TreeNode left = new TreeNode(in.nextInt());
        TreeNode right = new TreeNode(in.nextInt());

        curr.left = left;
        curr.right = right;

        q.add(left);
        q.add(right);
      }
      numNodes *= 2;
    }

    return root;
  }
}


import java.util.*;

public class OmNomAndDankPank {
  private static class TreeNode {
    public TreeNode left;
    public TreeNode right;
    public int val;

    public TreeNode(int val) {
      this.val = val;
    }

    public String preorder() {
      StringBuilder s = new StringBuilder();
      s.append(val + ",");

      if (left != null) {
        s.append(left.preorder());
      }
      if (right != null) {
        s.append(right.preorder());
      }

      return s.toString();
    }
  }

  private static int totalToAdd;

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    TreeNode root = constructTree(n, in);
    System.out.println(root.preorder());

    calc(root);
    System.out.println(totalToAdd);
  }

  // Returns the length of each path in root.
  private static int calc(TreeNode root) {
    if (root.left == null && root.right == null) {
      return 0;
    }

    int leftLength = calc(root.left) + root.left.val;
    int rightLength = calc(root.right) + root.right.val;

    totalToAdd += Math.abs(leftLength - rightLength);
    return Math.max(leftLength, rightLength);
  }

  private static TreeNode constructTree(int n, Scanner in) {
    TreeNode root = new TreeNode(0);
    Queue<TreeNode> q = new LinkedList<TreeNode>();
    q.add(root);
    int numNodes = 1;

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < numNodes; j++) {
        TreeNode curr = q.remove();
        TreeNode left = new TreeNode(in.nextInt());
        TreeNode right = new TreeNode(in.nextInt());

        curr.left = left;
        curr.right = right;

        q.add(left);
        q.add(right);
      }
      numNodes *= 2;
    }

    return root;
  }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProblemB {
    BufferedReader rd;

    private ProblemB() throws IOException {
        rd = new BufferedReader(new InputStreamReader(System.in));
        compute();
    }

    private void compute() throws IOException {
        int n = pint();
        int p = 1 << (n+1);
        int[] a = new int[p];
        int[] c = new int[p];
        int[] b = intarr();
        System.arraycopy(b,0,a,2,b.length);
        int res = 0;
        for(int i=(p>>1)-1;i>=1;i--) {
            int d = Math.abs(a[i*2]+c[i*2] - a[i*2+1]-c[i*2+1]);
            res += d;
            if(a[i*2] > a[i*2+1]) {
                c[i] = a[i*2] + c[i*2];
            } else {
                c[i] = a[i*2+1] + c[i*2+1];
            }
        }
        out(res);
    }

    private int pint() throws IOException {
        return pint(rd.readLine());
    }

    private int pint(String s) {
        return Integer.parseInt(s);
    }

    private int[] intarr() throws IOException {
        return intarr(rd.readLine());
    }

    private int[] intarr(String s) {
        String[] q = split(s);
        int n = q.length;
        int[] a = new int[n];
        for(int i=0;i<n;i++) {
            a[i] = Integer.parseInt(q[i]);
        }
        return a;
    }

    private String[] split(String s) {
        int n = s.length();
        int sp = 0;
        for(int i=0;i<n;i++) {
            if(s.charAt(i)==' ') {
                sp++;
            }
        }
        String[] res = new String[sp+1];
        int last = 0;
        int x = 0;
        for(int i=0;i<n;i++) {
            char c = s.charAt(i);
            if(c == ' ') {
                res[x++] = s.substring(last,i);
                last = i+1;
            }
        }
        res[x] = s.substring(last,n);
        return res;
    }

    private static void out(Object x) {
        System.out.println(x);
    }

    public static void main(String[] args) throws IOException {
        new ProblemB();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProblemB {
    BufferedReader rd;

    private ProblemB() throws IOException {
        rd = new BufferedReader(new InputStreamReader(System.in));
        compute();
    }

    private void compute() throws IOException {
        int n = pint();
        int p = 1 << (n+1);
        int[] a = new int[p];
        int[] c = new int[p];
        int[] b = intarr();
        System.arraycopy(b,0,a,2,b.length);
        int res = 0;
        for(int i=(p>>1)-1;i>=1;i--) {
            res += Math.abs(a[i*2]+c[i*2]-a[i*2+1]-c[i*2+1]);
            c[i] = Math.max(a[i*2]+c[i*2],a[i*2+1]+c[i*2+1]);
        }
        out(res);
    }

    private int pint() throws IOException {
        return pint(rd.readLine());
    }

    private int pint(String s) {
        return Integer.parseInt(s);
    }

    private int[] intarr() throws IOException {
        return intarr(rd.readLine());
    }

    private int[] intarr(String s) {
        String[] q = split(s);
        int n = q.length;
        int[] a = new int[n];
        for(int i=0;i<n;i++) {
            a[i] = Integer.parseInt(q[i]);
        }
        return a;
    }

    private String[] split(String s) {
        int n = s.length();
        int sp = 0;
        for(int i=0;i<n;i++) {
            if(s.charAt(i)==' ') {
                sp++;
            }
        }
        String[] res = new String[sp+1];
        int last = 0;
        int x = 0;
        for(int i=0;i<n;i++) {
            char c = s.charAt(i);
            if(c == ' ') {
                res[x++] = s.substring(last,i);
                last = i+1;
            }
        }
        res[x] = s.substring(last,n);
        return res;
    }

    private static void out(Object x) {
        System.out.println(x);
    }

    public static void main(String[] args) throws IOException {
        new ProblemB();
    }
}


import java.util.*;
import java.io.*;
public class B {
    public static void main(String args[]) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw=new PrintWriter(new OutputStreamWriter(System.out));
        //BufferedWriter bw=new BufferedWriter(pw);
        int n=Integer.parseInt(br.readLine());
        int a[]=new int[1<<(n+1)];
        String s=br.readLine();
        String ar[]=new String[(1<<(n+1))-2];
        ar=s.split(" ");
        int j=2;
        for(int i=0;i<ar.length;i++){
          a[j]=Integer.parseInt(ar[i]);
          j++;
        }
        /*for(int i=2;i<=7;i++){
            System.out.println(a[i]+"dsd");
        }*/
        int ans=0;
        for(int i=(1<<n)-1;i>=1;i--){
            int x=a[2*i];
            //System.out.println(a[7]+"fsfrw");
            int y=a[(2*i)+1];
          //  System.out.println(i+" "+x+" "+y);
            ans+=(2*Math.max(x, y))-x-y;
            a[i]+=Math.max(x, y);
          //  System.out.println(ans);
        }
        pw.print(ans);
        pw.flush();
    }
}


import java.util.*;
import java.io.*;
public class B {
    public static void main(String args[]) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw=new PrintWriter(new OutputStreamWriter(System.out));
        //BufferedWriter bw=new BufferedWriter(pw);
        int n=Integer.parseInt(br.readLine());
        int a[]=new int[1<<(n+1)];
        String s=br.readLine();
        String ar[]=new String[(1<<(n+1))-2];
        ar=s.split(" ");
        for(int i=0;i<ar.length;i++){
          a[i+1]=Integer.parseInt(ar[i]);
        }
        int ans=0;
        for(int i=(1<<n)-1;i>=1;i--){
            int x=a[2*i];
            int y=a[(2*i)+1];
            a[i]=Math.max(x, y);
            ans+=2*a[i]-x-y;
        }
        pw.print(ans);
        pw.flush();
    }
}


import java.io.*;
import java.util.*;
public class housie{
    public static void main(String args[]){
        Scanner s=new Scanner(System.in);
        //int n=s.nextInt();
        String st=s.nextLine();
        String []str=st.split(" ");
        int W=Integer.parseInt(str[0]);
        int val[] =new int[2];
        int wt[] = new int[2];
        val[0]=Integer.parseInt(str[1]);
        val[1]=Integer.parseInt(str[2]);
        wt[0]=Integer.parseInt(str[3]);
        wt[1]=Integer.parseInt(str[4]);
        //System.out.println(val[0]+" "+val[1]);
        //System.out.println(W);
//int  W = 50;
        int n = 2;
        int valu= knapSack(W, wt, val, n);
        System.out.println(valu);

    }
public static int knapSack(int W, int wt[], int val[], int n)
{
   int i, w;
   int K[][]=new int[n+1][W+1];

   // Build table K[][] in bottom up manner
   for (i = 0; i <= n; i++)
   {
       for (w = 0; w <= W; w++)
       {
           if (i==0 || w==0)
               K[i][w] = 0;
           else if (wt[i-1] <= w)
                 K[i][w] = Math.max((val[i-1] + K[i][w-wt[i-1]]),  K[i-1][w]);
           else
                 K[i][w] = K[i-1][w];
        //   System.out.print(K[i][w]+"    ");
       }
      // System.out.println();
   }

   return K[n][W];
}
}


import java.util.*;
import java.math.*;

/**
 *
 * @author sarthak
 */

public class zeptoLabcodeRush_B {
   static HashMap<Integer,Boolean> lvs=new HashMap<>();
   static int[][] lm;
   public static  int dfs(int v)
   {
       if(lvs.containsKey(v))return 0;

       int lf=dfs(2*v);
       int rf=dfs(2*v+1);
       return Math.max(lf+lm[v][2*v],rf+ lm[v][2*v+1]);
   }

    public static void main(String[] args)
    {
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        lm=new int[(int)Math.pow(2, n+1)][(int)Math.pow(2, n+1)];
        for(int i=2;i<=(int)Math.pow(2, n+1)-1;i++)
          lm[i/2][i]=s.nextInt();
        int[] sv=new int[100000];
        int mxl=Integer.MIN_VALUE;
        for(int lf=(int)Math.pow(2,n);lf<(int)Math.pow(2,n+1);lf++)
        {
            int ex=lf;
            int cl=0;
            while(ex!=1)
            {
                cl+=lm[ex/2][ex];
                ex=ex/2;
            }
            sv[lf]=cl;
            mxl=Math.max(mxl, cl);
            //System.out.println(mxl);
        }
        for(int i=(int)Math.pow(2, n);i<(int)Math.pow(2, n+1);i++)
            lvs.put(i, Boolean.TRUE);

        int an=0;
        int[] dp=new int[(int)Math.pow(2, n+1)];//dp[i] num of changes between i n i/2
        dp[1]=0;
        int[] pf=new int[(int)Math.pow(2, n+1)];

        for(int i=2;i<(int)Math.pow(2, n+1);i++)
        {

           int j=i/2;int fr=0;//from root
           int tl=dfs(i);//to leaf

           while(j!=1)
           {

               fr+=dp[j]+lm[j/2][j];
               j=j/2;
           }
           fr+=lm[i/2][i];

           dp[i]=mxl-tl-fr;
           an+=dp[i];

        }
        System.out.println(an);

        }

        //System.out.println(an);
    }


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;

public class Main
{
    static int[] a;
    static int m,ans=0;
    public static void cal(int k)
    {
        ans+=Math.abs(a[2*k+1]-a[2*k]);
        a[k]+=Math.max(a[2*k+1],a[2*k]);
        if(k>1)
        cal(k-1);
    }
    public static void main(String args[])throws Exception
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());
        m=(int)Math.pow(2,n+1);
        int k=(int)Math.pow(2,n)-1;
        a=new int[m];
        st=new StringTokenizer(br.readLine());
        for(int i=2;i<m;i++)
        {
            a[i]=Integer.parseInt(st.nextToken());
        }
        cal(k);
        System.out.print(ans);
    }
}