fun main(args: Array<String>) {
    var first =  readLine()!!.split(' ');
    var second =  readLine()!!.split(' ');

    var ans = 0;
    val arr= IntArray(3000) { it + 1 }

    for(i in 1..first.size-1) {
        var x = 1;
        for (j in 1..second.size - 1)
            if (first[i] == second[j]) x = 0
        if(x == 1){
            arr[ans] = first[i].toInt()
            ans++;
        }
    }
    for(i in 1..second.size-1) {
        var x = 1;
        for (j in 1..first.size - 1)
            if (second[i] == first[j]) x = 0
        if(x == 1){
            arr[ans] = second[i].toInt()
            ans++;
        }
    }

    print(ans)
    for(i in 0..ans-1) print(" "+arr[i])
}


fun main(args: Array<String>) {

    val s1 = readLine()!!.split(' ').map(String::toInt)
    val s2 = readLine()!!.split(' ').map(String::toInt)

    val sz1 = s1[0]
    val sz2 = s2[0]

    //println(sz1)
    //println(sz2)

    val arr = Array(2222,{0})

    for (x in 1..sz1){
        arr[s1[x] + 1000] = arr[s1[x]+1000] + 1
    }

    for (x in 1..sz2){
        arr[s2[x] + 1000] = arr[s2[x]+1000] + 1
    }

    var ans = 0
    for(x in 0..2000){
        if(arr[x] == 1){
            ans++
        }
    }

    print(ans)

    for(x in 0..2000){
        if(arr[x] == 1){
            print(' ')
            print(x-1000)

        }
    }
}


fun main(args: Array<String>) {

    val s1 = readLine()!!.split(' ').map(String::toInt)
    val s2 = readLine()!!.split(' ').map(String::toInt)

    val sz1 = s1[0]
    val sz2 = s2[0]

    //println(sz1)
    //println(sz2)

    val arr = Array(2222,{0})

    for (x in 1..sz1){
        arr[s1[x] + 1000] = arr[s1[x]+1000] + 1
    }

    for (x in 1..sz2){
        arr[s2[x] + 1000] = arr[s2[x]+1000] + 1
    }

    for(x in 0..2000){
        if(arr[x] == 1){
            print(x-1000)
            print(' ')
        }
    }
}


import java.util.*
import kotlin.io.*

fun main(args: Array<String>) {

    var a = readLine()!!.split(" ")

    var n1 = a[0].toString().toInt()

    var m1 = Array(n1, { i -> (i * i).toInt() })

    var b = readLine()!!.split(" ")

    var n2 = b[0].toString().toInt()

    var m2 = Array(n2, { i -> (i * i).toInt() })

    for (i in 1..n1) {
        m1[i - 1] = a[i].toString().toInt()
    }

    for (i in 1..n2) {
        m2[i - 1] = b[i].toString().toInt()
    }

    m1.sort()
    m2.sort()

    var al = 0
    var ar = m1.size - 1
    var bl = 0
    var br = m2.size - 1

    var res: String = ""
    var ptr: Int = 0

    while ((al <= ar) && (bl <= br)) {
        if (m1[al] < m2[bl]) {
            ptr++
            res = res + m1[al] + " "
            System.err?.println(m1[al])
            al++
        } else if (m1[al] > m2[bl]) {
            ptr++
            res = res + m2[bl] + " "
            System.err?.println(m2[bl])
            bl++
        } else {
            al++
            bl++
        }
    }
    while (al <= ar) {
        ptr++
        res = res + m1[al] + " "
        System.err?.println(m1[al++])
    }
    while (bl <= br) {
        ptr++
        res = res + m2[bl] + " "
        System.err?.println(m2[bl++])
    }
    print(ptr)
    print(" ")
    println(res)

}


test=int(input())
for t in range (0,test):
    n, m=map(int,input().split())
    a = list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        print(sum(a)*2)
        for i in range (0,m-1):
            print(i+1,i+2)
        print(n,1)


import sys
# merge sort algorithm for Python

def merge(arr, l, m, r):
	n1 = m-l+1
	n2 = r-m
	L = [0]*n1
	R = [0]*n2
	for i in range(n1):
		L[i] = arr[l+i]
	for j in range(n2):
		R[j] = arr[m+1+j]
	i = 0
	j = 0
	k = l
	while i<n1 and j<n2:
		if L[i] >= R[j]:
			arr[k] = R[j]
			j+=1
		else:
			arr[k] = L[i]
			i+=1
		k+=1
	while i < n1:
		arr[k] = L[i]
		k+=1
		i+=1
	while j < n2:
		arr[k] = R[j]
		k+=1
		j+=1
def mergeSort(arr, l, r):
	if l < r:
		m = l + (r-l)//2
		mergeSort(arr, l, m)
		mergeSort(arr, m+1, r)
		merge(arr, l, m, r)

T=int(input())
for _ in range(T):
	n,m=map(int,input().split())
	array=[int(i)for i in input().split()]
	if m < n:
		print(-1)
		continue
	# so otherwise, it should be possible
	# firstly, we need to sort the numbers in the array (merge sort), and then the answer should be 2*sum(all of the fridges) + (m-n) * (sum of smallest two)
	array_initial = array[:]
	mergeSort(array, 0, n-1)
	p = 1 + array_initial.index(array[0])
	q = 1 + array_initial.index(array[1])
	sys.stdout.write(str(2*sum(array)+(m-n)*(array[0]+array[1]))+"\n")
	for i in range(m-n):
		sys.stdout.write("{one} {two}\n".format(one=p,two=q))
	for i in range(n):
		sys.stdout.write("{one} {two}\n".format(one=1+i%n,two=1+(i+1)%n))


import sys
# merge sort algorithm for Python

def merge(arr, l, m, r):
	n1 = m-l+1
	n2 = r-m
	L = [0]*n1
	R = [0]*n2
	for i in range(n1):
		L[i] = arr[l+i]
	for j in range(n2):
		R[j] = arr[m+1+j]
	i = 0
	j = 0
	k = l
	while i<n1 and j<n2:
		if L[i] >= R[j]:
			arr[k] = R[j]
			j+=1
		else:
			arr[k] = L[i]
			i+=1
		k+=1
	while i < n1:
		arr[k] = L[i]
		k+=1
		i+=1
	while j < n2:
		arr[k] = R[j]
		k+=1
		j+=1
def mergeSort(arr, l, r):
	if l < r:
		m = l + (r-l)//2
		mergeSort(arr, l, m)
		mergeSort(arr, m+1, r)
		merge(arr, l, m, r)

T=int(input())
for _ in range(T):
	n,m=map(int,input().split())
	array=[int(i)for i in input().split()]
	if m < n or n == 2:
		print(-1)
		continue
	# so otherwise, it should be possible
	# firstly, we need to sort the numbers in the array (merge sort), and then the answer should be 2*sum(all of the fridges) + (m-n) * (sum of smallest two)
	array_initial = array[:]
	mergeSort(array, 0, n-1)
	p = 1 + array_initial.index(array[0])
	q = 1 + array_initial.index(array[1])
	sys.stdout.write(str(2*sum(array)+(m-n)*(array[0]+array[1]))+"\n")
	for i in range(m-n):
		sys.stdout.write("{one} {two}\n".format(one=p,two=q))
	for i in range(n):
		sys.stdout.write("{one} {two}\n".format(one=1+i%n,two=1+(i+1)%n))


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int,input().split())

def solve():
	n, m = mints()
	r = sum(mints())
	if m == n and n > 2:
		print(r)
		for i in range(1,n):
			print(i, i+1)
		print(n, 1)
	else:
		print(-1)

for i in range(mint()):
	solve()


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int,input().split())

def solve():
	n, m = mints()
	r = sum(mints())*2
	if m == n and n > 2:
		print(r)
		for i in range(1,n):
			print(i, i+1)
		print(n, 1)
	else:
		print(-1)

for i in range(mint()):
	solve()


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 20:01:46 2019

@author: DELL
"""

a=int(input())
for i in range(a):
    n, m=map(int,input().split(' '))
    l=[int(x) for x in input().split(' ')]
    if m<n:
        print("-1")
    elif n==2:
        print("-1")
    else:
        sum=0
        for i in range(n):
            sum=sum+l[i]
        sum=2*sum
        t=l
        t.sort()
        w=t[0]
        x=t[1]
        sum=sum+((m-n)*(w+x))
        print(sum)
        for i in range(n-1):
            print((i+1),end=" ")
            print((i+2))
        print("1",end=" ")
        print(n)
        if w!=x:
            q=l.index(w)
            r=l.index(x)
            for i in range((m-n)):
                print((q+1),end=" ")
                print((r+1))
        else:
            k=[]
            for i in range(n):
                if l[i]==w:
                    k.append(i)
            for i in range((m-n)):
                print((k[0]+1),end=" ")
                print((k[1]+1))


for _ in range(int(input())):
    a,b=map(int,input().split())
    l=list(map(int,input().split()))
    t=0;c=0;ll1=[];ll2=[]
    if b<a or b>((a-1)*a)//2:
        print('-1')
    else:
        c=1;ll1.append(a);ll2.append(1)
        t+=l[a-1];t+=l[0]
        for i in range(a-1):
            ll1.append(i+1)
            t+=l[i]+l[i+1]
            ll2.append(i+2)
            c+=1
            if c>=b:
                break
        for i in range(0,a,2):
            if c>=b:
                break
            else:
                t+=l[i]+l[i+2]
                ll1.append(i+1)
                ll2.append(i+3)
                c+=1
        for i in range(2,a+1,2):
            if c>=b:
                break
            else:
                t+=l[i]+l[i+2]
                ll1.append(i)
                ll2.append(i+2)
                c+=1
        print(t)
        for i in range(len(ll1)):
            print(ll1[i],ll2[i])


for _ in range(int(input())):
    a,b=map(int,input().split())
    l=list(map(int,input().split()))
    t=0;c=0;ll1=[];ll2=[]
    if b<a or b>((a-1)*a)//2:
        print('-1')
    else:
        for i in range(a-1):
            ll1.append(i+1)
            t+=l[i]+l[i+1]
            ll2.append(i+2)
            c+=1
            if c>=b:
                break
        for i in range(0,a,2):
            if c>=b:
                break
            else:
                t+=l[i]+l[i+2]
                ll1.append(i+1)
                ll2.append(i+3)
                c+=1
        for i in range(2,a+1,2):
            if c>=b:
                break
            else:
                t+=l[i]+l[i+2]
                ll1.append(i)
                ll2.append(i+2)
                c+=1
        print(t)
        for i in range(len(ll1)):
            print(ll1[i],ll2[i])


for _ in range(int(input())):
    a,b=map(int,input().split())
    l=list(map(int,input().split()))
    if b<a or b>((a-1)*a)//2:
        print('-1')
    else:
        print(2*sum(l))
        for i in range(a):
            print(i+1,(i+1)%a+1)


for i in range(int(input())):
    n,m=map(int,input().split())
    a=[0] + list(map(int,input().split()))
    b=[[-1,i] for i in range(n+1)]
    if m< (2*n - 3) or n==2:
        print(-1)
    else:
        for i in range(n+1):
            b[i][0]=a[i]
        b.sort()
        ans=0
        pr=[]
        # print(b)
        ind1=b[1][1]
        ind2=b[2][1]
        ind3=b[3][1]
        # print(ind1,ind2,ind3)
        for i in range(2,n+1):
            if i!=ind2:
                pr.append([i,ind1])
                pr.append([i,ind2])
                ans+=(2*a[i] + a[ind1] + a[ind2])
            else:
                pr.append([i,ind1])
                ans+=(a[i] + a[ind1])

        # print(ans)

        for i in range(m- 2*n +3):
            pr.append([ind2,ind1])
            ans+=(a[ind2] + a[ind1])
        print(ans)
        for i in pr:
            print(*i)


for i in range(int(input())):
    n,m=map(int,input().split())
    a=[0] + list(map(int,input().split()))
    b=[[-1,i] for i in range(n+1)]
    if m< (n) or n==2:
        print(-1)
    else:
        for i in range(n+1):
            b[i][0]=a[i]
        b.sort()
        ans=0
        pr=[]
        # print(b)
        ind1=b[1][1]
        ind2=b[2][1]
        ind3=b[3][1]
        # print(ind1,ind2,ind3)
        ans=0
        ans=2*sum(a)
        pr.append([1,n])
        for i in range(1,n):
            pr.append([i,i+1])
            # ans+=(a[i] + a[i+1])

        # print(ans)

        for i in range(m- n):
            pr.append([ind2,ind1])
            ans+=(a[ind2] + a[ind1])
        print(ans)
        for i in pr:
            print(*i)


n=int(input())
arr=[]
d={}
for i in range(n-2):
    a,b,c=map(int,input().split())
    arr.append([a,b,c])
    d[a]=d.get(a,[]) + [i]
    d[b]=d.get(b,[]) + [i]
    d[c]=d.get(c,[]) + [i]
# print(d)
for i in d:
    if len(d[i])==1:
        ind=d[i][0]

vis=[0]*(n-2)
visno=[0]*(n+1)
q=[arr[ind]]
vis[ind]=1
# print(d)
# print(arr)
if len(d[q[0][0]])==1:
    print(q[0][0],end=" ")
    visno[q[0][0]]=1

elif len(d[q[0][1]])==1:
    print(q[0][1],end=" ")
    visno[q[0][1]]=1

else:
    print(q[0][2],end=" ")
    visno[q[0][2]]=1

# print(q)

if len(d[q[0][0]])==2:
    print(q[0][0],end=" ")
    visno[q[0][0]]=1
    prev=q[0][0]
    if len(d[q[0][0]])==2:
        for i in (d[q[0][0]]):
            if vis[i]==0:
                q.append(arr[i])
                vis[i]=1

elif len(d[q[0][1]])==2:
    print(q[0][1],end=" ")
    visno[q[0][1]]=1
    prev=q[0][1]
    if len(d[q[0][1]])==2:
        for i in (d[q[0][1]]):
            if vis[i]==0:
                q.append(arr[i])
                vis[i]=1

else:
    print(q[0][2],end=" ")
    visno[q[0][2]]=1
    prev=q[0][2]
    if len(d[q[0][2]])==2:
        for i in (d[q[0][2]]):
            if vis[i]==0:
                q.append(arr[i])
                vis[i]=1
# q.pop(0)
# print(q)
for i in range(n-4):
    p=q.pop(0)
    for j in p:
        if visno[j]==0:
            visno[j]=1
            for k in d[j]:
                if vis[k]==0:
                    vis[k]=1
                    q.append(arr[k])
                    print(j,end=" ")
                    break
            break
q.pop(0)
# print(q)
for j in q[0]:
    if len(d[j])==2:
        print(j,end=" ")

for j in q[0]:
    if len(d[j])==1:
        print(j,end=" ")

# for i in range()


for i in range(int(input())):
    n,m=map(int,input().split())
    a=[0] + list(map(int,input().split()))
    b=[[-1,i] for i in range(n+1)]
    if m< (n*(n-1))//2 or n==2:
        print(-1)
    else:
        for i in range(n+1):
            b[i][0]=a[i]
        b.sort()
        ans=0
        pr=[]
        # print(b)
        ind1=b[1][1]
        ind2=b[2][1]
        ind3=b[3][1]
        # print(ind1,ind2,ind3)
        for i in range(2,n+1):
            if i!=ind2:
                pr.append([i,ind1])
                pr.append([i,ind2])
                ans+=(2*a[i] + a[ind1] + a[ind2])
            else:
                pr.append([i,ind1])
                ans+=(a[i] + a[ind1])

        # print(ans)

        for i in range(m- 2*n +3):
            pr.append([ind2,ind1])
            ans+=(a[ind2] + a[ind1])
        print(ans)
        for i in pr:
            print(*i)


t = int(input())
for _ in range(t):
    n, m = map(int, input().split())
    a = [(i+1, c) for i, c in enumerate(map(int, input().split()))]
    a = sorted(a, key=lambda x: x[1])
    # minc = a[0][1] + a[1][1]
    # mine = str(a[0][0]) + ' ' + str(a[1][0])
    sumc = 0
    for i in range(n):
        sumc += a[i][1]
    # print(a)
    # print(minc)
    # print(mine)
    if m < n or n == 2:
        print(-1)
    else:
        ans = 2 * sumc  # + minc * (m - n)
        print(ans)
        for i in range(1, n):
            print(i, i+1)
        print(n, 1)
        # for i in range(m - n):
        #     print(mine)


t = int(input())
for _ in range(t):
    n, m = map(int, input().split())
    a = [(i+1, c) for i, c in enumerate(map(int, input().split()))]
    a = sorted(a, key=lambda x: x[1])
    minc = a[0][1] + a[1][1]
    mine = str(a[0][0]) + ' ' + str(a[1][0])
    sumc = 0
    for i in range(n):
        sumc += a[i][1]
    # print(a)
    # print(minc)
    # print(mine)
    if m < n:
        print(-1)
    else:
        ans = 2 * sumc + minc * (m - n)
        print(ans)
        for i in range(1, n):
            print(i, i+1)
        print(n, 1)
        for i in range(m - n):
            print(mine)


t = int(input())
for _ in range(t):
    n, m = map(int, input().split())
    a = [(i+1, c) for i, c in enumerate(map(int, input().split()))]
    a = sorted(a, key=lambda x: x[1])
    # minc = a[0][1] + a[1][1]
    # mine = str(a[0][0]) + ' ' + str(a[1][0])
    sumc = 0
    for i in range(n):
        sumc += a[i][1]
    # print(a)
    # print(minc)
    # print(mine)
    if m < n:
        print(-1)
    else:
        ans = 2 * sumc  # + minc * (m - n)
        print(ans)
        for i in range(1, n):
            print(i, i+1)
        print(n, 1)
        # for i in range(m - n):
        #     print(mine)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or m < n:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(n):
            if pr == m:
                break
            for j in range(i + 1, n):
                if pr == m:
                    break
                ans += a[i][0] + a[j][0]
                anss.append((a[i][1], a[j][1]))
                pr += 1
            if pr == m:
                break
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or n > m:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(n):
            if pr == m:
                break
            for j in range(i + 1, n):
                if pr == m:
                    break
                ans += a[i][0] + a[j][0]
                anss.append((a[i][1], a[j][1]))
                pr += 1
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or m < n:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    a.append(a[0])
    ans = 0
    anss = []
    pr = 0
    for i in range(1, n + 1):
        ans += a[i - 1][0] + a[i][0]
        anss.append((a[i - 1][1], a[i][1]))
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n==2 or m < n:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    # a.sort()
    a.append(a[0])
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(1, n + 1):
            if pr == m:
                break
            ans += a[i - 1][0] + a[i][0]
            anss.append((a[i - 1][1], a[i][1]))
            pr += 1
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or m > n:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(n):
            if pr == m:
                break
            for j in range(i + 1, n):
                if pr == m:
                    break
                ans += a[i][0] + a[j][0]
                anss.append((a[i][1], a[j][1]))
                pr += 1
            if pr == m:
                break
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or n - 1 >= m:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(n):
            if pr == m:
                break
            for j in range(i + 1, n):
                if pr == m:
                    break
                ans += a[i][0] + a[j][0]
                anss.append((a[i][1], a[j][1]))
                pr += 1
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if m < n:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    # a.sort()
    a.append(a[0])
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(1, n + 1):
            if pr == m:
                break
            ans += a[i - 1][0] + a[i][0]
            anss.append((a[i - 1][1], a[i][1]))
            pr += 1
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or n >= m:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(n):
            if pr == m:
                break
            for j in range(i + 1, n):
                if pr == m:
                    break
                ans += a[i][0] + a[j][0]
                anss.append((a[i][1], a[j][1]))
                pr += 1
    print(ans)
    for i in anss:
        print(*i)


for _ in range(int(input())):
    n, m = map(int, input().split())
    a = [int(x) for x in input().split()]
    if n == 2 and m == 1 or m < n:
        print(-1)
        continue
    for i in range(len(a)): a[i] = (a[i], i + 1)
    a.sort()
    a.append(a[0])
    ans = 0
    anss = []
    pr = 0
    while pr != m:
        for i in range(1, n + 1):
            if pr == m:
                break
            ans += a[i - 1][0] + a[i][0]
            anss.append((a[i - 1][1], a[i][1]))
            pr += 1
    print(ans)
    for i in anss:
        print(*i)


from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline()
for _ in range(ii()):
    n, m=mi()
    a=li()
    s=[]
    if n>2 and m>=n:
        s.append([1, n])
        for i in range(1, n):
            s.append([i, i+1])
        x=sum(a)*2
        z=min(a)
        u=a.index(z)
        a.remove(z)
        y=min(a)
        v=a.index(y)
        if v>=u:
            v+=1
        print(x+((z+y)*(m-n)))
        for i in s:
            print(*i)
        for _ in range(m-n):
            print(u+1, v+1)
    else:
        print(-1)


cases = int(input())

for _ in range(cases):
    ppl, chains = map(int, input().strip().split())
    w = list(map(int, input().strip().split()))
    weights = [(w[i], i + 1) for i in range(len(w))]
    weights.sort()
    ans = 0
    c = 0
    if ppl < 3:
        print(-1)
        continue
    elif ppl == 3:
        if chains < 3:
            print(-1)
            continue
        ans += weights[2][0] * 2 + weights[1][0] + weights[0][0]
        ans += (chains - 2) * (weights[0][0] + weights[1][0])
        print(ans)
        print(weights[2][1], weights[1][1])
        print(weights[2][1], weights[0][1])
        for _ in range(chains - 2):
            print(weights[0][1], weights[1][1])
        continue
    elif chains < (ppl - 2) * 2:
        print(-1)
        continue
    else:
        links = []
        for i in range(2, len(weights)):
            ans += weights[0][0] + weights[i][0] * 2 + weights[1][0]
            c += 2
            links.append((weights[0][1], weights[i][1]))
            links.append((weights[1][1], weights[i][1]))
        ans += (chains - c) * (weights[0][0] + weights[1][0])
        print(ans)
        for x, y in links:
            print(x, y)
        for _ in range(chains - c):
            print(weights[0][1], weights[1][1])
        continue
    print(-1)


cases = int(input())

for _ in range(cases):
    ppl, chains = map(int, input().strip().split())
    w = list(map(int, input().strip().split()))
    weights = [(w[i], i + 1) for i in range(len(w))]
    weights.sort()
    if ppl == 2 or chains < ppl - 1:
        print(-1)
        continue
    ans = 0
    for i in range(ppl):
        ans += w[i] * 2
    ans += (chains - ppl) * (weights[0][0] + weights[1][0])
    print(ans)
    for i in range(1, ppl):
        print(i, i + 1)
    print(1, ppl)
    for _ in range(chains - ppl):
        print(weights[0][1], weights[1][1])


cases = int(input())

for _ in range(cases):
    ppl, chains = map(int, input().strip().split())
    w = list(map(int, input().strip().split()))
    weights = [(w[i], i + 1) for i in range(len(w))]
    weights.sort()
    if ppl == 2 or chains < ppl - 1:
        print(-1)
        continue
    ans = 0
    for i in range(ppl):
        ans += w[i] * 2
    ans += (chains - ppl) * (weights[0][0] + weights[1][0])
    print(ans)
    for i in range(1, ppl - 1):
        print(i + 1, i + 2)
    print(1, ppl)
    for _ in range(chains - (ppl - 1)):
        print(weights[0][1], weights[1][1])


cases = int(input())

for _ in range(cases):
    ppl, chains = map(int, input().strip().split())
    w = list(map(int, input().strip().split()))
    weights = [(w[i], i + 1) for i in range(len(w))]
    weights.sort()
    if ppl == 2 or chains < ppl:
        print(-1)
        continue
    ans = 0
    for i in range(ppl):
        ans += w[i] * 2
    ans += (chains - ppl) * (weights[0][0] + weights[1][0])
    print(ans)
    for i in range(1, ppl):
        print(i, i + 1)
    print(1, ppl)
    for _ in range(chains - ppl):
        print(weights[0][1], weights[1][1])


test_cases = int(input())
for t in range(test_cases):
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    if( m < n-1):
        print(-1)
    elif( m == n):
        print(2*sum(a))
        for index in range(len(a)-1):
            print(index,index+1)
        print(len(a)-1,0)


test_cases = int(input())
for t in range(test_cases):
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    if( m < n-1):
        print(-1)
    elif( m == n):
        print(2*sum(a))
        for index in range(len(a)-1):
            print(index+1,index+2)
        print(len(a),1)


test_cases = int(input())
for t in range(test_cases):
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    if( m < n-1 or m <= 2):
        print(-1)
    elif( m == n):
        print(2*sum(a))
        for index in range(len(a)-1):
            print(index+1,index+2)
        print(len(a),1)


import numpy as geek
for _ in range(int(input())):
	n,m = map(int,input().split())
	arr = list(map(int,input().split()))
	n_arr = geek.array(arr)
	o_arr = geek.argsort(n_arr)
	new_arr=  (list(o_arr))
	for i in range(len(new_arr)):
		new_arr[i] +=  1
	new_arr.append(new_arr[0])

	if m==n:
		print (sum(arr)*2)
		for i in range(m):
			print(new_arr[i],new_arr[i+1])
	else:
		print (-1)


for _ in range(int(input())):
	n,m = map(int,input().split())
	arr = list(map(int,input().split()))
	if n>m or n==2:
		print (-1)
	else:
		print (sum(arr)*2)
		for j in range(1,m):
			print(j,j+1)
		print (1,n)


def small(arr):

    freq={}

    for i in range(len(arr)):
        freq[arr[i]]=i

    #print(freq)

    arr=list(set(arr))
    if(len(arr)==1 ):
        return (0,1)

    #print(arr)
    arr.sort()

    small=freq[arr[0]]
    sec_small=freq[arr[1]]

    return (small,sec_small)

def graph(arr,n,m):

    empty=[]
    a=1
    b=a+1

    temp=n

    sum=0

    while(temp>0):
        #print(a,b)
        if(a==n):
            a=n
            b=1
        empty.append((a,b))
        a=b
        b=a+1
        temp-=1

    for i in empty:
        sum+= arr[i[0]-1] + arr[i[1]-1]
        #print(i[0],i[1])

    min_sec=small(arr)

    lp=m-n

    while(lp>0):
        empty.append((min_sec[0]+1,min_sec[1]+1))
        sum+= arr[min_sec[0]] + arr[min_sec[1]]
        lp-=1
    #print(empty)

    print(sum)
    for i in empty:
        print(i[0],i[1])

t=int(input())
for i in range(t):
    inp=input().split()
    n=int(inp[0])
    m=int(inp[1])
    arr=list(map(int,input().split()))

    if(m<=n-1):
        print(-1)
    else:
        graph(arr,n,m)


def small(arr):

    freq={}

    for i in range(len(arr)):
        freq[arr[i]]=i

    #print(freq)

    arr=list(set(arr))
    if(len(arr)==1 ):
        return (0,1)

    #print(arr)
    arr.sort()

    small=freq[arr[0]]
    sec_small=freq[arr[1]]

    return (small,sec_small)

def graph(arr,n,m):

    empty=[]
    a=1
    b=a+1

    temp=n

    s=0
    s=sum(arr)*2

    while(temp>0):
        #print(a,b)
        if(a==n):
            a=n
            b=1
        empty.append((a,b))
        a=b
        b=a+1
        temp-=1

    print(s)
    for i in empty:
        print(i[0],i[1])

t=int(input())
for i in range(t):
    inp=input().split()
    n=int(inp[0])
    m=int(inp[1])
    arr=list(map(int,input().split()))

    if(m<=n-1 or n==2):
        print(-1)
    else:
        graph(arr,n,m)


t=int(input())
for i in range(t):
    n,m=map(int,input().split())
    l=list(map(int,input().split()))
    if(n==2 or n > m):
        print(-1)
    else:
        for i in range(n-1):
            print(i+1,i+2)
        print(n,1)


t=int(input())
for i in range(t):
    n,m=map(int,input().split())
    l=list(map(int,input().split()))
    if(n==2 or n > m):
        print(-1)
    else:
        print(sum(l)*2)
        for i in range(n-1):
            print(i+1,i+2)
        print(n,1)


T=int(input())
for t in range(0,T):
    n,m=map(int, input().split())
    A=list(map(int, input().split()))
    wt=sum(A)
    if m<n:
        print(-1)
    else:
        if m==n:
            print(2*wt)
        else:
            m1=min(A)
            B=A
            B.remove(m1)
            m2=min(B)
            print(2*wt + (m-n)*(m1+m2))
            for i in range(0,(m-n)):
                print(A.index(m1), A.index(m2))
        for i in range(1,n):
            print(i, i+1)
        print(n, 1)


T=int(input())
for t in range(0,T):
    n,m=map(int, input().split())
    A=list(map(int, input().split()))
    wt=sum(A)
    if m<n or n<=2:
        print(-1)
    else:
        if m==n:
            print(2*wt)
        else:
            m1=min(A)
            B=A
            B.remove(m1)
            m2=min(B)
            print(2*wt + (m-n)*(m1+m2))
            for i in range(0,(m-n)):
                print(A.index(m1), A.index(m2))
        for i in range(1,n):
            print(i, i+1)
        print(n, 1)


import sys
import math
import itertools
import collections

def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def wr(arr): return ''.join(map(str, arr))
def revn(n): return str(n)[::-1]
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base):
    newnumber = 0
    while number > 0:
        newnumber += number % base
        number //= base
    return newnumber

t = ii()
for _ in range(t):
    n, m = mi()
    a = li()
    if n > m or n == 2:
        print(-1)
    else:
        ans = 2 * sum(a)
        mina = min(a)
        posmin = a.index(min(a))
        b = a.copy()
        b.sort()
        posmin1 = a.index(b[1])
        if posmin == posmin1:
            posmin1 = a.index(b[1], posmin + 1)
        ans += (mina + b[1]) * (m - n)
        print(ans)
        for i in range(n - 1):
            print(i + 1, i + 2)
        print(n, 1)
        for i in range(m - n):
            print(posmin + 1, posmin1 + 1)


import sys
import math
import itertools
import collections

def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def wr(arr): return ''.join(map(str, arr))
def revn(n): return str(n)[::-1]
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base):
    newnumber = 0
    while number > 0:
        newnumber += number % base
        number //= base
    return newnumber

t = ii()
for _ in range(t):
    n, m = mi()
    a = li()
    if n > m:
        print(-1)
    else:
        ans = 2 * sum(a)
        mina = min(a)
        posmin = a.index(min(a))
        b = a.copy()
        b.sort()
        posmin1 = a.index(b[1], posmin + 1)
        ans += (mina + b[1]) * (m - n)
        print(ans)
        for i in range(n - 1):
            print(i + 1, i + 2)
        print(n, 1)
        for i in range(m - n):
            print(posmin + 1, posmin1 + 1)


import sys
import math
import itertools
import collections

def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def wr(arr): return ''.join(map(str, arr))
def revn(n): return str(n)[::-1]
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base):
    newnumber = 0
    while number > 0:
        newnumber += number % base
        number //= base
    return newnumber

t = ii()
for _ in range(t):
    n, m = mi()
    a = li()
    if n > m or n == 2:
        print(-1)
    else:
        ans = 2 * sum(a)
        mina = min(a)
        posmin = a.index(min(a))
        b = a.copy()
        b.sort()
        posmin1 = a.index(b[1], posmin + 1)
        ans += (mina + b[1]) * (m - n)
        print(ans)
        for i in range(n - 1):
            print(i + 1, i + 2)
        print(n, 1)
        for i in range(m - n):
            print(posmin + 1, posmin1 + 1)


import sys
from collections import defaultdict as dd
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var))
def l(): return list(sp())
def strl(): return list(strsp())
def sp(): return map(int, data().split())
def strsp(): return map(str, data().split())

for _ in range(int(data())):
    n,m=sp()
    a=l()
    if m!=n:
        print(-1)
    else:
        print(2*sum(a))
        c,d=1,2
        for i in range(m):
            if d==n:
                print(c,d)
                d=1
                c+=1
            else:
                print(c,d)
                c+=1
                d+=1


import sys
from collections import defaultdict as dd
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var))
def l(): return list(sp())
def strl(): return list(strsp())
def sp(): return map(int, data().split())
def strsp(): return map(str, data().split())

for _ in range(int(data())):
    n,m=sp()
    a=l()
    if n==2:
        print(-1)
    elif m!=n:
        print(-1)
    else:
        print(2*sum(a))
        c,d=1,2
        for i in range(m):
            if d==n:
                print(c,d)
                d=1
                c+=1
            else:
                print(c,d)
                c+=1
                d+=1


from sys import stdin
import math

def inp():
	return stdin.readline().strip()

t = int(inp())
for _ in range(t):
	n, m = [int(x) for x in inp().split()]
	ar = [int(x) for x in inp().split()]
	if m < n:
		print(-1)

	else:
		min1 = float('inf')
		min2 = float('inf')
		minpos1 = -1
		minpos2 = -1
		for i in range(n):
			if min(min2, ar[i]) < min2 and min(min2, ar[i]) >= min1:
				min2 = min(min2, ar[i])
				minpos2 = i+1
			if min(min1, ar[i]) < min1:
				if min(min2, min1) < min2:
					min2 = min(min2, min1)
					minpos2 = minpos1
				min1 = min(min1, ar[i])
				minpos1 = i+1
		print(2*sum(ar)+(m-n)*(min1+min2))
		for i in range(m):
			if i < n-1:
				print(i+1, end = " ")
				print(i+2)
			elif i == n-1:
				print(i+1, end = " ")
				print(1)
			else:
				print(minpos1, end=" ")
				print(minpos2)


from sys import stdin
import math

def inp():
	return stdin.readline().strip()

t = int(inp())
for _ in range(t):
	n, m = [int(x) for x in inp().split()]
	ar = [int(x) for x in inp().split()]
	if m < n or n <= 2:
		print(-1)

	else:
		min1 = float('inf')
		min2 = float('inf')
		minpos1 = -1
		minpos2 = -1
		for i in range(n):
			if min(min2, ar[i]) < min2 and min(min2, ar[i]) >= min1:
				min2 = min(min2, ar[i])
				minpos2 = i+1
			if min(min1, ar[i]) < min1:
				if min(min2, min1) < min2:
					min2 = min(min2, min1)
					minpos2 = minpos1
				min1 = min(min1, ar[i])
				minpos1 = i+1
		print(2*sum(ar)+(m-n)*(min1+min2))
		for i in range(m):
			if i < n-1:
				print(i+1, end = " ")
				print(i+2)
			elif i == n-1:
				print(i+1, end = " ")
				print(1)
			else:
				print(minpos1, end=" ")
				print(minpos2)


t=int(input())
for i in range(t):
    person_num,chains_num=map(int,input().split())
    fridges=list(map(int,input().split()))
    Last_fridges=fridges[:]
    fridges.sort()
    if person_num<=2 or chains_num<person_num:
        print(-1)
    else:
        money_1=2*sum(fridges)
        res=chains_num-person_num
        money_2=res*(fridges[0]+fridges[1])

        res1=fridges[0]
        res2=fridges[1]
        location1=Last_fridges.index(res1)
        location2=Last_fridges.index(res2)

        print(money_1+money_2)

        for x in range(person_num-1):
            print(x+1,x+2)
        print(1,person_num)

        for j in range(res):
            print(location1,location2)


t=int(input())
for i in range(t):
    person_num,chains_num=map(int,input().split())
    fridges=list(map(int,input().split()))
    fridges.sort()
    if person_num<=2 or chains_num<person_num:
        print(-1)
    else:
        money_1=2*sum(fridges)
        res=chains_num-person_num
        money_2=res*(fridges[0]+fridges[1])

        print(money_1+money_2)

        for x in range(person_num-1):
            print(fridges[x],fridges[x+1])
        print(fridges[0],fridges[-1])

        for j in range(res):
            print(fridges[0],fridges[1])


for t in range(int(input())):
    n,m=[int(x) for x in input().split()]
    a=[int(x) for x in input().split()]
    if n!=m or n==2:
        print(-1)
    else:
        print(2*sum(a))
        for i in range(n-1):
            print(i+1,i+2)
        print(n,1)


for t in range(int(input())):
    n,m=[int(x) for x in input().split()]
    a=[int(x) for x in input().split()]
    if n!=m:
        print(-1)
    else:
        print(2*sum(a))
        for i in range(n-1):
            print(i+1,i+2)
        print(n,1)


t=int(input());
for i in range(t):
    lis=input().split();
    n=int(lis[0]);
    m=int(lis[1]);
    lis1=input().split();
    k=0;
    if(n>m):
        print(-1);
    elif(n==m):
        sum1=0;
        for j in range(n):
            lis1[j]=int(lis1[j]);
            sum1+=lis1[j];
        print(sum1*2);
        for j in range(1,n):
            print(j,j+1);
        print(n,1);
    else:
        sum=0;
        sum1=0;
        sum2=0;
        for j in range(n):
            lis1[j]=int(lis1[j]);
            sum1+=lis1[j];
        sum2=sum1;
        lis1.sort();
        a=lis1[0];
        b=lis1[1];
        c=lis1[2];
        sum1=sum1-a;
        sum2=sum2-b;
        for j in range(n):
            if(j==0):
                sum+=sum1;
            elif(j==1):
                sum+=sum2;
            else:
                sum+=a+b;
        k=m-(n-2+n-1);
        sum+=k*(a+b);
        print(sum);
        for j in range(n):
            if(j==0):
                print(1,2);
            elif(j==1):
                print(1+1,2+1);
            else:
                if(j!=2):
                    print(j+1,1);
                    print(j+1,2);
                else:
                    print(j+1,1);
        for j in range(k):
            print(1,2);


t=int(input());
for i in range(t):
    lis=input().split();
    n=int(lis[0]);
    m=int(lis[1]);
    lis1=input().split();
    if(n>m):
        print(-1);
    elif(n==m):
        sum1=0;
        for j in range(n):
            lis1[j]=int(lis1[j]);
            sum1+=lis1[j];
        print(sum1*2);
        for j in range(1,n):
            print(j,j+1);
        print(n,1);
    else:
        sum=0;
        sum1=0;
        sum2=0;
        for j in range(n):
            lis1[j]=int(lis1[j]);
            sum1+=lis1[j];
        sum2=sum1;
        lis1.sort();
        a=lis1[0];
        b=lis1[1];
        c=lis1[2];
        sum1=sum1-a;
        sum2=sum2-b;
        for j in range(n):
            if(j==0):
                sum+=sum1;
            elif(j==1):
                sum+=sum2;
            else:
                sum+=a+b;
        k=m-n;
        sum+=k*(a+b);
        print(sum);
        for j in range(n):
            if(j==0):
                print(1,2);
            elif(j==1):
                print(1+1,2+1);
            else:
                if(j!=2):
                    print(j+1,1);
                    print(j+1,2);
                else:
                    print(j+1,1);


t=int(input());
for i in range(t):
    lis=input().split();
    n=int(lis[0]);
    m=int(lis[1]);
    lis1=input().split();
    k=0;
    if(n==2):
        print(-1);
    elif(n>m):
        print(-1);
    elif(n==m):
        sum1=0;
        for j in range(n):
            lis1[j]=int(lis1[j]);
            sum1+=lis1[j];
        print(sum1*2);
        for j in range(1,n):
            print(j,j+1);
        print(n,1);
    else:
        sum=0;
        sum1=0;
        sum2=0;
        for j in range(n):
            lis1[j]=int(lis1[j]);
            sum1+=lis1[j];
        sum2=sum1;
        lis1.sort();
        a=lis1[0];
        b=lis1[1];
        c=lis1[2];
        sum1=sum1-a;
        sum2=sum2-b;
        for j in range(n):
            if(j==0):
                sum+=sum1;
            elif(j==1):
                sum+=sum2;
            else:
                sum+=a+b;
        k=m-(n-2+n-1);
        sum+=k*(a+b);
        print(sum);
        for j in range(n):
            if(j==0):
                print(1,2);
            elif(j==1):
                print(1+1,2+1);
            else:
                if(j!=2):
                    print(j+1,1);
                    print(j+1,2);
                else:
                    print(j+1,1);
        for j in range(k):
            print(1,2);


test_case = int(input())
output = ''

for z in range(0,test_case):
    line = input().split()
    n, m = int(line[0]), int(line[1])
    wights = [int(x) for x in input().split()]
    if m < n : output += '-1\n'
    else:
        total_cost = 0
        for x in wights:
            total_cost += 2*x
        output += '%s\n'%total_cost
        for i in range(1, n):
            output += '%s %s\n'%(i , i + 1)
        output += '%s 1\n'%n

print(output[:-1])


test_case = int(input())
output = ''

for z in range(0,test_case):
    line = input().split()
    n, m = int(line[0]), int(line[1])
    wights = [int(x) for x in input().split()]
    if m < n or n == 2 : output += '-1\n'
    else:
        total_cost = 0
        for x in wights:
            total_cost += 2*x
        output += '%s\n'%total_cost
        for i in range(1, n):
            output += '%s %s\n'%(i , i + 1)
        output += '%s 1\n'%n

print(output[:-1])


t = int(input())
while t>0:
    t = t-1
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    qwer = 0
    zxc = 0
    if n == 2 or m < n:
        print(-1)
    else:
        for i in range(n-1):
            qwer += a[i]+a[i+1]
            zxc += 1
        qwer += a[0]+a[n-1]
        zxc += 1
        temp = [i for i in range(n)]
        zxczxc = zxc
        print(qwer)
        for i in range(n-1):
            print(i+1,i+2)
        print(n,1)
        while zxczxc < m:
            print(temp[0]+1,temp[1]+1)
            zxczxc +=1


t = int(input())
while t>0:
    t = t-1
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    qwer = 0
    zxc = 0
    if n == 2 or m < n:
        print(-1)

    else:
        for i in range(n-1):
            qwer += a[i]+a[i+1]
            zxc += 1
        qwer += a[0]+a[n-1]
        zxc += 1
        temp = [i for i in range(n)]

        xyz = [i[0] for i in sorted(enumerate(a), key=lambda x:x[1])]
        zxczxc = zxc
        while zxc < m:
            qwer += a[0]+ a[1]
        print(qwer)
        for i in range(n-1):
            print(i+1,i+2)
        print(n,1)
        while zxczxc < m:
            print(temp[0]+1,temp[1]+1)
            zxczxc +=1


def connect_fridges(n, m, prices):
    if m < n:
        return -1
    cumsum = 0
    ans = []
    order = sorted(range(len(prices)),key=prices.__getitem__)
    for i in range(n-1):
        cumsum += prices[order[i]] + prices[order[i+1]]
        ans.append([str(order[i]+1), str(order[i+1]+1)])
    cumsum += prices[order[-1]] + prices[order[0]]
    ans.append([str(order[-1]+1), str(order[0]+1)])
    for i in range(m-n):
        cumsum += prices[order[0]] + prices[order[1]]
        ans.append([str(order[0]+1), str(order[1]+1)])
    return cumsum, ans

if __name__ == '__main__':
    q = int(input())
    for i in range(q):
        n, m = map(int, input().split())
        prices = list(map(int, input().split()))
        result = connect_fridges(n, m, prices)
        if type(result) == int:
            print(result)
        else:
            print(result[0])
            for i in range(m):
                print(' '.join(result[1][i]))


def connect_fridges(n, m, prices):
    if m < n and n > 2:
        return -1
    cumsum = 0
    ans = []
    order = sorted(range(len(prices)),key=prices.__getitem__)
    for i in range(n-1):
        cumsum += prices[order[i]] + prices[order[i+1]]
        ans.append([str(order[i]+1), str(order[i+1]+1)])
    cumsum += prices[order[-1]] + prices[order[0]]
    ans.append([str(order[-1]+1), str(order[0]+1)])
    for i in range(m-n):
        cumsum += prices[order[0]] + prices[order[1]]
        ans.append([str(order[0]+1), str(order[1]+1)])
    return cumsum, ans

if __name__ == '__main__':
    q = int(input())
    for i in range(q):
        n, m = map(int, input().split())
        prices = list(map(int, input().split()))
        result = connect_fridges(n, m, prices)
        if type(result) == int:
            print(result)
        else:
            print(result[0])
            for i in range(m):
                print(' '.join(result[1][i]))


def connect_fridges(n, m, prices):
    if m < n and n > 2:
        return -1
    cumsum = 0
    ans = []
    order = sorted(range(len(prices)),key=prices.__getitem__)
    for i in range(n-1):
        cumsum += prices[order[i]] + prices[order[i+1]]
        ans.append([str(order[i]+1), str(order[i+1]+1)])
    cumsum += prices[order[-1]] + prices[order[0]]
    ans.append([str(order[-1]+1), str(order[0]+1)])
    return cumsum, ans

if __name__ == '__main__':
    q = int(input())
    for i in range(q):
        n, m = map(int, input().split())
        prices = list(map(int, input().split()))
        result = connect_fridges(n, m, prices)
        if type(result) == int:
            print(result)
        else:
            print(result[0])
            for i in range(m):
                print(' '.join(result[1][i]))


def connect_fridges(n, m, prices):
    if m < n or n <3:
        return -1
    cumsum = 0
    ans = []
    order = sorted(range(len(prices)),key=prices.__getitem__)
    for i in range(n-1):
        cumsum += prices[order[i]] + prices[order[i+1]]
        ans.append([str(order[i]+1), str(order[i+1]+1)])
    cumsum += prices[order[-1]] + prices[order[0]]
    ans.append([str(order[-1]+1), str(order[0]+1)])
    return cumsum, ans

if __name__ == '__main__':
    q = int(input())
    for i in range(q):
        n, m = map(int, input().split())
        prices = list(map(int, input().split()))
        result = connect_fridges(n, m, prices)
        if type(result) == int:
            print(result)
        else:
            print(result[0])
            for i in range(m):
                print(' '.join(result[1][i]))


t=int(input())
for i in range(t):
    n,m=map(int,input().split())
    l=list(map(int,input().split()))
    if n==2:
        print('-1')
    elif n>m:
        print('-1')
    else:
        print(sum(l)*2)
        for i in range(n-1):
            print(i+1,i+2)
        print(n,n-n+1)


t=int(input())
for i in range(t):
    n,m=map(int,input().split())
    l=list(map(int,input().split()))
    if n>m:
        print('-1')
    else:
        print(sum(l)*2)
        for i in range(n-1):
            print(i+1,i+2)
        print(n,n-n+1)


t=int(input())
while(t>0):
    t-=1
    n,m=map(int, input().split())
    arr=list(map(int,input().split()))
    if(m<=(n-1)):
        print("-1")
    elif(n==2):
        print("-1")
    else:
        sum=0
        for i in range(n):
            sum=sum+(arr[i]*2)
        print(sum)
        for i in range(1,n):
            print(i, i+1)
        print(n,1)


t=int(input())
while(t>0):
    t-=1
    n,m=map(int, input().split())
    arr=list(map(int,input().split()))
    if(m<=(n-1)):
        print("-1")
    else:
        sum=0
        for i in range(n):
            sum=sum+(arr[i]*2)
        print(sum)
        for i in range(1,n):
            print(i, i+1)
        print(n,1)


t=int(input())
while(t>0):
    t-=1
    n,m=map(int, input().split())
    arr=list(map(int,input().split()))
    if(m<(n-1)):
        print("-1")
    else:
        l={}
        sum=0
        min1=arr[n-1]
        min1_in=n-1
        min2=arr[0]
        min2_in=0
        for i in range(n):
            if(arr[i]<min1):
                min1=arr[i]
                min1_in=i
            sum=sum+(arr[i]*2)
        for i in range(n):
            if( (arr[i]<min1) and (i!=min1_in) and (arr[i]<min2) ):
                min2=arr[i]
                min2_in=i
        print(sum+  ( (m-n)*(min1+min2) ))
        #print("min1",min1,"min2",min2,"min in1",min1_in,"min2_in",min2_in)
        for i in range(1,n):
            sum+=(arr[i-1]+arr[i])
            print(i, i+1)
        print(n,1)

        d=m-n
        while(d>0):
            d-=1
            print(min1_in+1,min2_in+1)


t=int(input())
while(t>0):
    t-=1
    n,m=map(int, input().split())
    arr=list(map(int,input().split()))
    if(m<(n-1)):
        print("-1")
    else:
        l={}
        sum=0
        for i in range(n):
            sum=sum+(arr[i]*2)

        print(sum)
        for i in range(1,n):
            print(i, i+1)
        print(n,1)


t=int(input())
while(t>0):
    t-=1
    n,m=map(int, input().split())
    arr=list(map(int,input().split()))
    if(m<(n-1)):
        print("-1")
    else:
        l={}
        sum=0
        arr.sort()
        min1=arr[0]
        min2=arr[1]
        for i in range(n):
            sum=sum+(arr[i]*2)
        print(sum+  ( (m-n)*(min1+min2) ))
        for i in range(1,n):
            sum+=(arr[i-1]+arr[i])
            print(i, i+1)
        print(n,1)

        d=m-n
        while(d>0):
            d-=1
            print(min1,min2)


def sol():
    T = int(input())
    for i in range(T):

        n,m = map(int,input().split())
        a = list(map(int, input().split()))
        if n==2 or m<n :print('-1');continue
        dict = {}
        sum = 0
        for j in range(n):
            sum += a[j]
            dict[j+1] = a[j]
        d = sorted(dict.items(),key=lambda x:x[1])
        ans = sum*2 + (m-n)*(d[0][1]+d[1][1])
        print(ans)
        for j in range(1,n):
            print(j,' ',j+1)
        print(n,' ',1)
        for j in range(m-n):
            print(d[0][0],' ',d[1][0])

if __name__ == '__main__':
    sol()


def sol():
    T = int(input())
    for i in range(T):
        dict = {}
        n,m = map(int,input().split())
        a = list(map(int, input().split()))
        if n<2:print('-1');continue
        if n==2:print('-1');continue
        if n==3 and m<3:print('-1');continue
        if m<(n-2)*2:print('-1');continue
        for j in range(n):
            dict[j+1] = a[j]
        d = sorted(dict.items(),key=lambda x:x[1])
        ans = 0
        for c in range(2, n):
            ans += int(d[0][1]) + int(d[c][1])
            ans += int(d[1][1]) + int(d[c][1])
        ans += (m-(n-2)*2)*(int(d[0][1])+int(d[1][1]))
        print(ans)
        for c in range(2,n):
            print(d[0][0],' ',d[c][0])
            print(d[1][0],' ',d[c][0])
        for c in range(m-(n-2)*2):
            print(d[0][0], ' ', d[1][0])

if __name__ == '__main__':
    sol()


def sol():
    T = int(input())
    for i in range(T):
        dict = {}
        n,m = map(int,input().split())
        a = list(map(int, input().split()))
        if n==2:print('-1');continue
        if n==3 and m<3:print('-1');continue
        if m<(n-2)*2:print('-1');continue
        for j in range(n):
            dict[j+1] = a[j]
        d = sorted(dict.items(),key=lambda x:x[1])
        ans = 0
        for c in range(2, n):
            ans += int(d[0][1]) + int(d[c][1])
            ans += int(d[1][1]) + int(d[c][1])
        ans += (m-(n-2)*2)*(int(d[0][1])+int(d[1][1]))
        print(ans)
        for c in range(2,n):
            print(d[0][0],' ',d[c][0])
            print(d[1][0],' ',d[c][0])
        for c in range(m-(n-2)*2):
            print(d[0][0], ' ', d[1][0])

if __name__ == '__main__':
    sol()


t = int(input())

for i in range(t):
    n, m = map(int, input().split())
    a = list(enumerate(map(int, input().split()), 1))
    if m < n:
        print(-1)
        continue
    a = sorted(a, key = lambda x: x[1])
    ans = 0
    l = []
    for i in range(n-1):
        l.append([a[i][0], a[i+1][0]])
        ans += a[i][1]+a[i+1][1]
    ans += a[0][1]+a[n-1][1]
    l.append([a[0][0], a[n-1][0]])
    print(ans)
    for i in l:
        print(*i)


t = int(input())

for i in range(t):
    n, m = map(int, input().split())
    a = list(enumerate(map(int, input().split()), 1))
    if m < n or n == 2:
        print(-1)
        continue
    a = sorted(a, key = lambda x: x[1])
    ans = 0
    l = []
    for i in range(n-1):
        l.append([a[i][0], a[i+1][0]])
        ans += a[i][1]+a[i+1][1]
    ans += a[0][1]+a[n-1][1]
    l.append([a[0][0], a[n-1][0]])
    print(ans)
    for i in l:
        print(*i)


import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

# sys.setrecursionlimit(200000)
# mod = 10**9+7
# mod = 987

def lcm(a,b):
    return (a*b)//math.gcd(a,b)

def sort_dict(key_value):
    return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))

def list_input():
    return list(map(int,input().split()))

def num_input():
    return map(int,input().split())

def string_list():
    return list(input())

def solve():
    n,m = num_input()
    arr = list_input()
    if m < (n-2)*2:
        print(-1)
        return
    arr.sort()
    cost = 0
    ans = []
    for i in range(2,n):
        m -= 2
        ans.append((1,i+1))
        ans.append((2,i+1))
        cost += (arr[0]+arr[1]+(2*arr[i]))

    flag = True
    indx = 3
    temp = 3
    i = 2
    while m != 0:
        if flag:
            cost += (arr[0]+arr[1])
            ans.append((1,2))
            flag = False
        else:
            cost += (arr[i]+arr[indx])
            ans.append((i+1,indx+1))
            indx += 1
            if indx == n:
                temp += 1
                indx = temp
                i += 1
                if i == n:
                    break
        m -= 1
    if m != 0:
        print(-1)
        return

    print(cost)
    for (u,v) in ans:
        print(u,v)

t = int(input())
#t = 1
for _ in range(t):
    solve()


import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

# sys.setrecursionlimit(200000)
# mod = 10**9+7
# mod = 987

def lcm(a,b):
    return (a*b)//math.gcd(a,b)

def sort_dict(key_value):
    return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))

def list_input():
    return list(map(int,input().split()))

def num_input():
    return map(int,input().split())

def string_list():
    return list(input())

def solve():
    n,m = num_input()
    arr = list_input()

    if m < n or n <= 2:
        print(-1)
        return

    print(sum(arr)*2)
    for i in range(1,n):
        print(i,i+1)
    print(1,n)

t = int(input())
#t = 1
for _ in range(t):
    solve()


import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

# sys.setrecursionlimit(200000)
# mod = 10**9+7
# mod = 987

def lcm(a,b):
    return (a*b)//math.gcd(a,b)

def sort_dict(key_value):
    return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))

def list_input():
    return list(map(int,input().split()))

def num_input():
    return map(int,input().split())

def string_list():
    return list(input())

def solve():
    n,m = num_input()
    arr = list_input()
    if m < (n-2)*2:
        print(-1)
        return
    arr.sort()
    cost = 0
    ans = []
    for i in range(2,n):
        m -= 2
        ans.append((arr[0],arr[i]))
        ans.append((arr[1],arr[i]))
        cost += (arr[0]+arr[1]+(2*arr[i]))

    while m != 0:
        cost += (arr[0]+arr[1])
        ans.append((arr[0],arr[1]))
        m -= 1

    print(cost)
    for (u,v) in ans:
        print(u,v)

t = int(input())
#t = 1
for _ in range(t):
    solve()


import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

# sys.setrecursionlimit(200000)
# mod = 10**9+7
# mod = 987

def lcm(a,b):
    return (a*b)//math.gcd(a,b)

def sort_dict(key_value):
    return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))

def list_input():
    return list(map(int,input().split()))

def num_input():
    return map(int,input().split())

def string_list():
    return list(input())

def solve():
    n,m = num_input()
    arr = list_input()
    if m < (n-2)*2:
        print(-1)
        return
    arr.sort()
    cost = 0
    ans = []
    for i in range(2,n):
        m -= 2
        ans.append((1,i+1))
        ans.append((2,i+1))
        cost += (arr[0]+arr[1]+(2*arr[i]))

    while m != 0:
        cost += (arr[0]+arr[1])
        ans.append((1,2))
        m -= 1

    print(cost)
    for (u,v) in ans:
        print(u,v)

t = int(input())
#t = 1
for _ in range(t):
    solve()


def inp():
    return map(int, input().split())

def arr_enu():
    return [[i+1, int(x)] for i, x in enumerate(input().split())]

def get_col(arr, i):
    return [row[i] for row in arr]

for i in range(int(input())):
    n, m = inp()
    a = arr_enu()
    if (m < n):
        print(-1)
    else:
        a.sort(key=lambda x:x[1])
        print(sum(get_col(a,1)) * 2)

        for j in range(n):
            if (j == n - 1):
                print(a[j][0], a[0][0])
            else:
                print(a[j][0], a[j + 1][0])


def inp():
    return map(int, input().split())

def arr_inp():
    return [int(x) for x in input().split()]

for i in range(int(input())):
    n, m = inp()
    a = arr_inp()

    if (m < n or n == 2):
        print(-1)
    else:
        print(sum(a) * 2)

        for j in range(1,m):
            print(j, j+1)
        print(1,m)


def inp():
    return map(int, input().split())

def arr_enu():
    return [[i+1, int(x)] for i, x in enumerate(input().split())]

def get_col(arr, i):
    return [row[i] for row in arr]

for i in range(int(input())):
    n, m = inp()
    a = arr_enu()

    if (m < n or n==2):
        print(-1)
    else:
        a.sort(key=lambda x:x[1])
        print(sum(get_col(a,1)) * 2)

        for j in range(n):
            if (j == n - 1):
                print(a[j][0], a[0][0])
            else:
                print(a[j][0], a[j + 1][0])


for q in range(int(input())):
    n, m = [int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    r = []

    if m < n or n <= 2:
        print(-1)
    else:
        c = 0
        r += ['1 2']
        c += a[0] + a[1]
        for i in range(1, n-1):
            r.append(f'{i} {i + 2}')
            c += a[i-1] + a[i+1]
        r += [f'{n-1} {n}']
        c += a[n-1] + a[n-2]
        min1 = a.index(min(a))
        x = a[min1]
        mn2 = 100000
        min2 = 0
        for i in range(0, len(a)):
            if a[i] < mn2 and i != min1:
                mn2 = a[i]
                min2 = i
        y = a[min2]
        r += [f'{min1+1} {min2+1}'] * (m - n)
        c += (y+x)*(m-n)
        print(c)
        print("\n".join(r))


for q in range(int(input())):
    n, m = [int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    r = []

    if m < n or n < 2:
        print(-1)
    else:
        c = 0
        r += ['1 2']
        c += a[0] + a[1]
        for i in range(1, n-1):
            r.append(f'{i} {i + 2}')
            c += a[i-1] + a[i+1]
        r += [f'{n-1} {n}']
        c += a[n-1] + a[n-2]
        min1 = a.index(min(a))
        x = a[min1]
        mn2 = 100000
        min2 = 0
        for i in range(0, len(a)):
            if a[i] < mn2 and i != min1:
                mn2 = a[i]
                min2 = i
        y = a[min2]
        r += [f'{min1+1} {min2+1}'] * (m - n)
        c += (y+x)*(m-n)
        print(c)
        print("\n".join(r))


for q in range(int(input())):
    n, m = [int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    r = []

    if m < n or n <= 2:
        print(-1)
    else:
        c = 0
        r += ['1 2']
        c += a[0] + a[1]
        for i in range(1, n-1):
            r.append(f'{i} {i + 2}')
            c += a[i-1] + a[i+1]
        r += [f'{n-1} {n}']
        c += a[n-1] + a[n-2]
        min1 = a.index(min(a))
        x = a[min1]
        min2 = 100000
        for i in range(0, len(a)):
            if a[i] < min2 and i != min1:
                min2 = i
        y = a[min2]
        r += [f'{min1+1} {min2+1}'] * (m - n)
        c += (y+x)*(m-n)
        print(c)
        print("\n".join(r))


for q in range(int(input())):
    n, m = [int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    r = []

    if m < n or n <= 2:
        print(-1)
    else:
        c = 0
        r += ['1 2']
        c += a[0] + a[1]
        for i in range(1, n-1):
            r.append(f'{i} {i + 2}')
            c += a[i-1] + a[i+1]
        r += [f'{n-1} {n}']
        c += a[n-1] + a[n-2]
        min1 = a.index(min(a))+1
        x = a[min1-1]
        min2 = 100000
        for i in range(len(a)):
            if a[i] < min2 and i != min1 - 1:
                min2 = a[i]
        y = a[min2-1]
        r += [f'{min1} {min2}'] * (m - n)
        c += (y+x)*(m-n)
        print(c)
        print("\n".join(r))


for q in range(int(input())):
    n, m = [int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    r = []

    if m < n or n < 2:
        print(-1)
    else:
        c = 0
        r += ['1 2']
        c += a[0] + a[1]
        for i in range(1, n-1):
            r.append(f'{i} {i + 2}')
            c += a[i-1] + a[i+1]
        r += [f'{n-1} {n}']
        c += a[n-1] + a[n-2]
        min1 = a.index(min(a))
        x = a[min1]
        min2 = 100000
        for i in range(0, len(a)):
            if a[i] < min2 and i != min1:
                min2 = i
        y = a[min2]
        r += [f'{min1+1} {min2+1}'] * (m - n)
        c += (y+x)*(m-n)
        print(c)
        print("\n".join(r))


for _ in range(int(input())):
    n,m=map(int,input().split())
    arr=list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        brr=[]
        for i in range(n):
            brr.append([arr[i],i+1])
        brr=sorted(brr,key=lambda x:x[0])

        print(2*sum(arr))
        if n==3:
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            print(brr[1][1],brr[0][1])
        else:
            for i in range(2,n):
                print(brr[0][1],brr[i][1])
                print(brr[1][1],brr[i][1])


for _ in range(int(input())):
    n,m=map(int,input().split())
    arr=list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        brr=[]
        for i in range(n):
            brr.append([arr[i],i+1])
        brr=sorted(brr,key=lambda x:x[0])

        print(2*sum(arr))
        if n==3:
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            print(brr[1][1],brr[0][1])
        else:
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            for i in range(3,n):
                print(brr[0][1],brr[i][1])
                print(brr[1][1],brr[i][1])


for _ in range(int(input())):
    n,m=map(int,input().split())
    arr=list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        print(2*sum(arr))
        for i in range(1,n):
            print(i,i+1)
        print(1,n)


for _ in range(int(input())):
    n,m=map(int,input().split())
    arr=list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        brr=[]
        for i in range(n):
            brr.append([arr[i],i+1])
        for i in range(n-1):
            for j in range(n-i-1):
                if(brr[i][0]>brr[i+1][0]):
                    t=brr[i][0]
                    brr[i][0]=brr[i+1][0]
                    brr[i+1][0]=t
        print(2*sum(arr))
        if n==3:

            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            print(brr[1][1],brr[0][1])
        else:
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            for i in range(3,n):
                print(brr[0][1],brr[i][1])
                print(brr[1][1],brr[i][1])


for _ in range(int(input())):
    n,m=map(int,input().split())
    arr=list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        brr=[]
        for i in range(n):
            brr.append([arr[i],i+1])
        for i in range(n-1):
            for j in range(n-i-1):
                if(brr[i][0]>brr[i+1][0]):
                    t=brr[i][0]
                    brr[i][0]=brr[i+1][0]
                    brr[i+1][0]=t
        print(2*sum(arr))
        if n==3:
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            print(brr[1][1],brr[0][1])
        else:
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            for i in range(3,n):
                print(brr[0][1],brr[i][1])
                print(brr[1][1],brr[i][1])


for _ in range(int(input())):
    n,m=map(int,input().split())
    arr=list(map(int,input().split()))
    if n>m or n==2:
        print(-1)
    else:
        brr=[]
        for i in range(n):
            brr.append([arr[i],i+1])
        brr=sorted(brr,key=lambda x:x[0])
        cnt=0
        if n==3:
            print(2*sum(arr))
            print(brr[0][1],brr[2][1])
            print(brr[1][1],brr[2][1])
            print(brr[1][1],brr[0][1])
        else:
            for i in range(2,n):
                cnt+=(brr[0][0]+brr[i][0])
                cnt+=(brr[1][0]+brr[i][0])
            print(cnt)
            for i in range(2,n):
                print(brr[0][1],brr[i][1])
                print(brr[1][1],brr[i][1])


t = int(input())

for j in range(t):
    n, m = [int(x) for x in input().split()]
    ws = [int(x) for x in input().split()]
    if m < n:
        print(-1)
    else:
        ws = sorted(ws)
        total = 0
        ans = []
        for i in range(m):
            uIndex = i % n
            vIndex = (i+1)%n
            u = ws[uIndex]
            v = ws[vIndex]
            total += u + v
            ans.append(str(uIndex+1) + " " + str(vIndex + 1))
        print(total)
        print("\n".join(ans))


t = int(input())

for j in range(t):
    n, m = [int(x) for x in input().split()]
    ws = [int(x) for x in input().split()]
    if m < n or n <= 2:
        print(-1)
    else:
        ws = sorted(ws)
        total = 0
        ans = []
        for i in range(m):
            uIndex = i % n
            vIndex = (i+1)%n
            u = ws[uIndex]
            v = ws[vIndex]
            total += u + v
            ans.append(str(uIndex+1) + " " + str(vIndex + 1))
        print(total)
        print("\n".join(ans))


t = int(input())
while t > 0:
	t -= 1
	n, m = map(int, input().strip().split())
	a = list(map(int, input().strip().split()))
	if n > m or n == 2:
		print("-1")
	else:
		print(2 * sum(a))
		for i in range(1, n):
			print(i, i + 1)
		print(i + 1, 1)


#include <bits/stdc++.h>
using namespace std;
vector< vector<int> > orange;
vector<int> used;
int main(){
  int n,k;
  cin >> n >> k;
  for(int i=0;i<k;i++){
    vector<int> temp;
    int a;
    cin >> a;
    temp.push_back(a);
    orange.push_back(temp);
    used.push_back(a);
  }
  int kid=0;
  for(int i=1;i<n*k;i++){
    if(find(used.begin(),used.end(),i)==used.end()){
      orange[kid].push_back(i);
      kid++;
      kid%=n;
    }
  }
  for(int i=0;i<k;i++){
    for(int j=0;j<n;j++){
      cout << orange[i][j] << " ";
    }
    cout << "\n";
  }

}


#include <bits/stdc++.h>
using namespace std;
vector< vector<int> > orange;
vector<int> used;
int main(){
  int n,k;
  cin >> n >> k;
  for(int i=0;i<k;i++){
    vector<int> temp;
    int a;
    cin >> a;
    temp.push_back(a);
    orange.push_back(temp);
    used.push_back(a);
  }
  int kid=0;
  for(int i=1;i<=n*k;i++){
    if(find(used.begin(),used.end(),i)==used.end()){
      orange[kid].push_back(i);
      kid++;
      kid%=n;
    }
  }
  for(int i=0;i<k;i++){
    for(int j=0;j<n;j++){
      cout << orange[i][j] << " ";
    }
    cout << "\n";
  }

}


#include <bits/stdc++.h>
using namespace std;
vector<int> used;
int main(){
  int n,k;
  cin >> n >> k;
  for(int i=0;i<k;i++){
    int a;
    cin >> a;
    used.push_back(a);
  }
  int kid=1;
  int last=1;
  for(int i=0;i<k;i++){
    cout << used[i] << " ";
    while(kid!=n){
      if(find(used.begin(),used.end(),last)==used.end()){
        cout << last << " ";

        kid++;
      }
      last++;
    }
    kid=1;
    cout << "\n";
  }

}


#include <bits/stdc++.h>
#define endl '\n'
#define debug(X) cout << #X << " = " << X << endl
#define fori(i,b,e) for (int i = (b); i < (e); ++i)
#define mod(x,m) ((((x) % (m)) + (m)) % (m))
#define sq(x) (x) * (x)

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;

const int oo = 1e9, mxn = 1000;

int A[mxn];

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	memset(A, -1, sizeof A);
	int n, k; cin >> n >> k;
	fori(i, 0, k) {
		int x; cin >> x; x--;
		A[x] = i;
	}
	int curr = 0, cnt = 0;
	fori(i, 0, n * k) {
		if (A[i] != -1) continue;
		A[i] = curr;
		cnt++;
		if (cnt == n - 1) curr++, cnt = 0;
	}
	vector<vi> ans(k);
	fori(i, 0, n * k)
		ans[A[i]].push_back(i);
	fori(i, 0, ans.size()) {
		fori(j, 0, ans[i].size())
			cout << ans[i][j] + 1 << " ";
		cout << endl;
	}
	return 0;
}


#include <bits/stdc++.h>
#define endl '\n'
#define debug(X) cout << #X << " = " << X << endl
#define fori(i,b,e) for (int i = (b); i < (e); ++i)
#define mod(x,m) ((((x) % (m)) + (m)) % (m))
#define sq(x) (x) * (x)

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;

const int oo = 1e9, mxn = 100;

int A[mxn];

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	memset(A, -1, sizeof A);
	int n, k; cin >> n >> k;
	fori(i, 0, k) {
		int x; cin >> x; x--;
		A[x] = i;
	}
	int curr = 0, cnt = 0;
	fori(i, 0, n * k) {
		if (A[i] != -1) continue;
		A[i] = curr;
		cnt++;
		if (cnt == n - 1) curr++, cnt = 0;
	}
	vector<vi> ans(k);
	fori(i, 0, n * k)
		ans[A[i]].push_back(i);
	fori(i, 0, ans.size()) {
		fori(j, 0, ans[i].size())
			cout << ans[i][j] + 1 << " ";
		cout << endl;
	}
	return 0;
}


// Codeforces Round #150 - Problem A: Dividing Orange (https://codeforces.com/problemset/problem/244/A)
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using ii = pair<ll, ll>;

#define REP(i, a, b) for (int (i) = (a); (i) <= (b); (i)++)
#define REPN(i, N) for (int (i) = 0; (i) < N; (i)++)
#define DEC(i, b, a) for (int (i) = (b); (i) >= (a); (i)--)
#define DECN(i, N) for (int (i) = N - 1; (i) >= 0; (i)--)

#define LOG(var, sep) (cerr << #var << " = " << (var) << (sep))
#define LOGM(msg) (cerr << (msg))
#define LOGV(vec, sep) { cerr << #vec << " ="; for (const auto& v : (vec)) cerr << " " << v; cerr << (sep); }
#define LOGA(arr, N, sep) { cerr << #arr << " ="; for (int i = 0; i < N; ++i) cerr << " " << (arr)[i]; cerr << (sep); }
#define LOGA2(arr, N, M, sep) { cerr << #arr << " =\n"; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) cerr << (arr)[i][j] << " "; cerr << endl; } cerr << (sep); }

ostream& operator<<(ostream& os, const ii& p)
{
    os << "(" << p.first << ", " << p.second << ")";
    return os;
}

const int MAX { 2000010 };
const int oo { 2000000010 };
const int MOD { 1000000007 };

int as[MAX];

void solve(int N, int K)
{
    set<int> used;

    REP(i, 1, K)
        used.insert(as[i]);

    // Laranjas não escolhidas por nenhuma criança
    vector<int> oranges;

    REP(i, 1, N*K)
    {
        if (used.count(i))
            continue;

        oranges.push_back(i);
    }

    int pos = 0;

    REP(i, 1, K)
    {
        cout << as[i];

        REPN(j, N - 1)
            cout << " " << oranges[pos++];

        cout << endl;
    }
}

int main()
{
    ios::sync_with_stdio(false);

    int N, K;
    cin >> N >> K;

    REP(i, 1, K)
        cin >> as[i];

    solve(N, K);

    return 0;
}


// Contest - Problem X: Name (link)
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using ii = pair<ll, ll>;

#define REP(i, a, b) for (int (i) = (a); (i) <= (b); (i)++)
#define REPN(i, N) for (int (i) = 0; (i) < N; (i)++)
#define DEC(i, b, a) for (int (i) = (b); (i) >= (a); (i)--)
#define DECN(i, N) for (int (i) = N - 1; (i) >= 0; (i)--)

#define LOG(var, sep) (cerr << #var << " = " << (var) << (sep))
#define LOGM(msg) (cerr << (msg))
#define LOGV(vec, sep) { cerr << #vec << " ="; for (const auto& v : (vec)) cerr << " " << v; cerr << (sep); }
#define LOGA(arr, N, sep) { cerr << #arr << " ="; for (int i = 0; i < N; ++i) cerr << " " << (arr)[i]; cerr << (sep); }
#define LOGA2(arr, N, M, sep) { cerr << #arr << " =\n"; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) cerr << (arr)[i][j] << " "; cerr << endl; } cerr << (sep); }

ostream& operator<<(ostream& os, const ii& p)
{
    os << "(" << p.first << ", " << p.second << ")";
    return os;
}

const int MAX { 2000010 };
const int oo { 2000000010 };
const int MOD { 1000000007 };

int as[MAX];

void solve(int N, int K)
{
    set<int> used;

    REP(i, 1, K)
        used.insert(as[i]);

    // Laranjas não escolhidas por nenhuma criança
    vector<int> oranges;

    REP(i, 1, N*K)
    {
        if (used.count(i))
            continue;

        oranges.push_back(i);
    }

    int pos = 0;

    REP(i, 1, K)
    {
        cout << as[i];

        REPN(j, N - 1)
            cout << " " << oranges[pos++];

        cout << endl;
    }
}

int main()
{
    ios::sync_with_stdio(false);

    int N, K;
    cin >> N >> K;

    REP(i, 1, N)
        cin >> as[i];

    solve(N, K);

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    int n;
    cin >> n;
    long long a[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    long long low = 1, high = 1e9;
    long long k = 1e10;
    long long mx = -1;
    while (low <= high)
    {
        long long mid = (low + high) / 2;
        bool ok = true;
        int ans = 0;
        int count = -1;
        int temp = 0;
        for (int i = 0; i < n; i++)
        {
            if (a[i] < mid)
            {
                temp++;
            }
            else
            {
                if (count > 0 && temp != count && temp > 0)
                {
                    ok = false;
                    break;
                }
                else if (temp == count)
                {
                    ans++;
                }
                else if (count == -1 && temp > 0)
                {
                    count = temp;
                    ans++;
                }
                temp = 0;
            }
        }
        if (temp > 0 && count > 0 && temp != count)
        {
            ok = false;
        }
        else if (temp == count)
        {
            ans++;
        }
        else if (count == -1 && temp > 0)
        {
            ans++;
        }
        if (ok)
        {
            if (mx <= ans)
            {
                mx = ans;
                k = min(k, mid);
                high = mid - 1;
            }
            else
            {
                low = mid + 1;
            }
        }
        else
        {
            low = mid + 1;
        }
    }
    cout << k << "\n";
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    int n;
    cin >> n;
    long long a[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    long long low = 1, high = 1e9;
    long long k = 1e10;
    long long mx = -1;
    while (low <= high)
    {
        long long mid = (low + high) / 2;
        bool ok = true;
        int ans = 0;
        int count = -1;
        int temp = 0;
        for (int i = 0; i < n; i++)
        {
            if (a[i] < mid)
            {
                temp++;
            }
            else
            {
                if (count > 0 && temp != count && temp > 0)
                {
                    ok = false;
                    break;
                }
                else if (temp == count)
                {
                    ans++;
                }
                else if (count == -1 && temp > 0)
                {
                    count = temp;
                    ans++;
                }
                temp = 0;
            }
        }
        if (temp > 0 && count > 0 && temp != count)
        {
            ok = false;
        }
        else if (temp == count)
        {
            ans++;
        }
        else if (count == -1 && temp > 0)
        {
            ans++;
        }
        if (ok)
        {
            if (mx <= ans)
            {
                mx = ans;
                k = mid;
                high = mid - 1;
            }
            else
            {
                low = mid + 1;
            }
        }
        else
        {
            low = mid + 1;
        }
        // cout << mid << " " << ans << " " << ok << "\n";
    }
    cout << k << "\n";
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    int n;
    cin >> n;
    pair<long long, int> a[n];
    pair<long long, int> b[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i].first;
        a[i].second = i;
        b[i] = {a[i].first, 1};
    }
    sort(a, a + n);
    long long k = 0;
    int pos;
    int seg = 0;
    int max_seg = 0;
    vector<int> count(n + 1, 0);
    int len;
    if (n == 1)
    {
        cout << a[0].first + 1 << "\n";
        return 0;
    }
    for (int i = 0; i < n; i++)
    {
        pos = a[i].second;
        if (pos == 0)
        {
            if (b[1].first < b[0].first)
            {
                b[0].second = b[1].second + 1;
                b[b[1].second].second += 1;
                len = b[0].second;
                count[len - 1] -= 1;
                count[len] += 1;
            }
            else
            {
                b[0].second = 1;
                len = 1;
                count[1] += 1;
                seg++;
            }
        }
        else if (pos == n - 1)
        {
            if (b[pos].first > b[pos - 1].first)
            {
                b[pos].second = b[pos - 1].second + 1;
                b[pos - b[pos - 1].second].second += 1;
                len = b[pos].second;
                count[len - 1] -= 1;
                count[len] += 1;
            }
            else
            {
                b[pos].second = 1;
                len = 1;
                count[len] += 1;
                seg++;
            }
        }
        else
        {
            if (b[pos - 1].first < b[pos].first && b[pos].first > b[pos + 1].first)
            {
                seg--;
                count[b[pos - 1].second] -= 1;
                count[b[pos + 1].second] -= 1;
                len = b[pos - 1].second + 1 + b[pos + 1].second;
                b[pos - b[pos - 1].second].second = len;
                b[pos + b[pos + 1].second].second = len;
                count[len] += 1;
            }
            else if (b[pos - 1].first < b[pos].first)
            {
                len = b[pos - 1].second + 1;
                count[len - 1] -= 1;
                b[pos - len + 1].second = len;
                b[pos].second = len;
                count[len] += 1;
            }
            else if (b[pos].first > b[pos + 1].first)
            {
                len = b[pos + 1].second + 1;
                count[len - 1] -= 1;
                b[pos + len - 1].second = len;
                b[pos].second = len;
                count[len] += 1;
            }
            else
            {
                b[pos].second = 1;
                seg++;
                len = 1;
                count[len] += 1;
            }
        }
        if (seg == count[len])
        {
            if (max_seg < seg)
            {
                max_seg = seg;
                k = a[i].first + 1;
            }
        }
    }
    cout << k << "\n";
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    int n;
    cin >> n;
    pair<long long, int> a[n];
    pair<long long, int> b[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i].first;
        a[i].second = i;
        b[i] = {a[i].first, 1};
    }
    sort(a, a + n);
    long long k = 0;
    int pos;
    int seg = 0;
    int max_seg = 0;
    vector<int> count(n + 1, 0);
    int len;
    for (int i = 0; i < n; i++)
    {
        pos = a[i].second;
        if (pos == 0)
        {
            if (b[1].first < b[0].first)
            {
                b[0].second = b[1].second + 1;
                b[b[1].second].second += 1;
                len = b[0].second;
                count[len - 1] -= 1;
                count[len] += 1;
            }
            else
            {
                b[0].second = 1;
                len = 1;
                count[1] += 1;
                seg++;
            }
        }
        else if (pos == n - 1)
        {
            if (b[pos].first > b[pos - 1].first)
            {
                b[pos].second = b[pos - 1].second + 1;
                b[pos - b[pos - 1].second].second += 1;
                len = b[pos].second;
                count[len - 1] -= 1;
                count[len] += 1;
            }
            else
            {
                b[pos].second = 1;
                len = 1;
                count[len] += 1;
                seg++;
            }
        }
        else
        {
            if (b[pos - 1].first < b[pos].first && b[pos].first > b[pos + 1].first)
            {
                len = b[pos - 1].second + 1 + b[pos + 1].second;
                b[pos - b[pos - 1].second].second = len;
                b[pos + b[pos + 1].second].second = len;
                seg--;
                count[b[pos - 1].second] -= 1;
                count[b[pos + 1].second] -= 1;
                count[len] += 1;
            }
            else if (b[pos - 1].first < b[pos].first)
            {
                len = b[pos - 1].second + 1;
                b[pos - len + 1].second = len;
                b[pos].second = len;
                count[len - 1] -= 1;
                count[len] += 1;
            }
            else if (b[pos].first > b[pos + 1].first)
            {
                len = b[pos + 1].second + 1;
                b[pos + len - 1].second = len;
                b[pos].second = len;
                count[len - 1] -= 1;
                count[len] += 1;
            }
            else
            {
                b[pos].second = 1;
                seg++;
                len = 1;
                count[len] += 1;
            }
        }
        if (seg == count[len])
        {
            if (max_seg < seg)
            {
                max_seg = seg;
                k = a[i].first + 1;
            }
        }
    }
    cout << k << "\n";
}


/*input
6
25 1 2 3 14 36

*/
#include<bits/stdc++.h>
#include<algorithm>
#include <fstream>
#include <sstream>
#include <string>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
using namespace __gnu_pbds;
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define is insert
#define rep1(i,a,b) for(long long i=a;i<=b;i++)
#define mp make_pair
#define mh make_heap
#define F first
#define S second
//#define fin cin
//#define fout cout
#define file ifstream fin("input.txt");ofstream fout("output.txt");
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fr(n) for(long long i=0;i<n;i++)
#define rep(i,a,b) for(long long i=a;i<b;i++)
#define ALL(x) (x).begin(), (x).end()
typedef long long int ll;
typedef long double ld;
#define lb lower_bound
#define ub uper_bound
#define bs lower_bound
//#define db(i) cout<<i<<endl;
typedef pair<ll,ll> pairs;
typedef vector<ll> vi;
typedef vector<pairs> vpair;
//find_by_order()  // order_of_key
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;
typedef tree<pair<int,int>, null_type, less<pair<int,int> >, rb_tree_tag,
tree_order_statistics_node_update> pbds;
struct compare{
  bool operator()(const pairs &a, const pairs &b)const{
    if(a.first == b.first) return a.second < b.second;
    return a.first > b.first;
  }
};

vi v[500000],link(500000),siz(500000),ind[500000];
multiset<ll>ms;
ll max_siz,min_val;

ll fin(ll x)
{
	if(link[x]==x)
		return x;
	return link[x]=fin(link[x]);
}

void connect(ll a,ll b)
{
	//cout<<"come :"<<a<<" "<<b<<endl;
	a=fin(a);
	if(link[b]!=0)
		b=fin(b);
	//cout<<"par "<<a<<" "<<b<<endl;
	if(a>b)swap(a,b);
	siz[a]+=siz[b];
	link[b]=a;
}

void solve()
{
	ll n;cin>>n;
	vi v(n);
	fr(n+1)siz[i]=1;
	rep(i,0,n)
	{
		cin>>v[i];
		ind[v[i]].pb(i+1);
	}
	sort(ALL(v));
	rep(i,0,n)
	{
		//cout<<"i:"<<i<<endl;
		if(!ms.empty())
		{
			if(*ms.begin()==(*(--ms.end())))
			{
				//cout<<"here"<<endl;
				if(max_siz<ms.size())
				{
					max_siz=ms.size();
					min_val=v[i];
				}
			}
		}
		rep(j,0,ind[v[i]].size())
		{
			ll k=ind[v[i]][j];
			//cout<<"k :"<<k<<endl;
			if(link[k-1]==0 && link[k+1]==0)
				link[k]=k;
			else
			{
				//cout<<"connecting"<<endl;
				if(link[k-1]!=0)
				{
					//cout<<"called "<<k-1<<endl;
					//cout<<"called "<<k-1<<" "<<fin(k-1)<<" "<<siz[fin(k-1)]<<" "<<ms.size()<<" "<<*ms.begin()<<endl;
					ms.erase(ms.find(siz[fin(k-1)]));
					connect(k-1,k);
				}
				if(link[k+1]!=0)
				{
					//cout<<"called "<<k+1<<" "<<fin(k+1)<<" "<<siz[fin(k+1)]<<" "<<ms.size()<<" "<<*ms.begin()<<endl;
					ms.erase(ms.find(siz[fin(k+1)]));
					connect(k+1,k);
				}
				//cout<<"connected"<<endl;
			}
			//cout<<"link[k] "<<link[k]<<endl;
			ms.is(siz[fin(k)]);
			/*cout<<"siz: "<<ms.size()<<endl;
			if(!ms.empty())
			{
				multiset<ll>::iterator it=ms.begin();
				for(it;it!=ms.end();it++)
					cout<<*it<<" ";
			}
			cout<<endl<<endl;*/
		}
	}
	cout<<min_val<<endl;
}
int main()
{
	fast;
    ll t=1;
    for(int i=0;i<t;i++)
    	solve();
}
//10-b-0
//11-b-friction


/*input
8

1 2 7 3 4 8 5 6
*/
#include<bits/stdc++.h>
#include<algorithm>
#include <fstream>
#include <sstream>
#include <string>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
using namespace __gnu_pbds;
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define is insert
#define rep1(i,a,b) for(long long i=a;i<=b;i++)
#define mp make_pair
#define mh make_heap
#define F first
#define S second
//#define fin cin
//#define fout cout
#define file ifstream fin("input.txt");ofstream fout("output.txt");
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fr(n) for(long long i=0;i<n;i++)
#define rep(i,a,b) for(long long i=a;i<b;i++)
#define ALL(x) (x).begin(), (x).end()
typedef long long int ll;
typedef long double ld;
#define lb lower_bound
#define ub uper_bound
#define bs lower_bound
//#define db(i) cout<<i<<endl;
typedef pair<ll,ll> pairs;
typedef vector<ll> vi;
typedef vector<pairs> vpair;
//find_by_order()  // order_of_key
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;
typedef tree<pair<int,int>, null_type, less<pair<int,int> >, rb_tree_tag,
tree_order_statistics_node_update> pbds;
struct compare{
  bool operator()(const pairs &a, const pairs &b)const{
    if(a.first == b.first) return a.second < b.second;
    return a.first > b.first;
  }
};

vi link(500000),siz(500000);
map<ll,ll>ind;
multiset<ll>ms;
ll max_siz,min_val;

ll fin(ll x)
{
	if(link[x]==x)
		return x;
	return link[x]=fin(link[x]);
}

void connect(ll a,ll b)
{
	a=fin(a);
	b=fin(b);
	if(siz[a]<siz[b])swap(a,b);
	siz[a]+=siz[b];
	link[b]=a;
}

void solve()
{
	ll n;cin>>n;
	vi v(n);
	rep(i,1,n+1)siz[i]=1;
	rep(i,0,n)
	{
		cin>>v[i];
		ind[v[i]]=i+1;
	}
	sort(ALL(v));
	max_siz=0;
	rep(i,0,n)
	{
		if(!ms.empty())
		{
			if(*ms.begin()==(*(--ms.end())))
			{
				if(max_siz<ms.size())
				{
					max_siz=ms.size();
					min_val=v[i-1]+1;
				}
			}
		}
		ll k=ind[v[i]];
		link[k]=k;
		if(link[k-1]!=0 && k>1)
		{
			ms.erase(ms.find(siz[fin(k-1)]));
			connect(k-1,k);
		}
		if(link[k+1]!=0 && k<n)
		{
			ms.erase(ms.find(siz[fin(k+1)]));
			connect(k+1,k);
		}
		ms.is(siz[fin(k)]);
	}
	if(!ms.empty())
	{
		if(*ms.begin()==(*(--ms.end())))
		{
			if(max_siz<ms.size())
			{
				max_siz=ms.size();
				min_val=v[n-1]+1;
			}
		}
	}

	cout<<min_val<<endl;
}
int main()
{
	fast;
    ll t=1;
    for(int i=0;i<t;i++)
    	solve();
}
//10-b-0
//11-b-friction


/*input
6
25 1 2 3 14 36

*/
#include<bits/stdc++.h>
#include<algorithm>
#include <fstream>
#include <sstream>
#include <string>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
using namespace __gnu_pbds;
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define is insert
#define rep1(i,a,b) for(long long i=a;i<=b;i++)
#define mp make_pair
#define mh make_heap
#define F first
#define S second
//#define fin cin
//#define fout cout
#define file ifstream fin("input.txt");ofstream fout("output.txt");
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fr(n) for(long long i=0;i<n;i++)
#define rep(i,a,b) for(long long i=a;i<b;i++)
#define ALL(x) (x).begin(), (x).end()
typedef long long int ll;
typedef long double ld;
#define lb lower_bound
#define ub uper_bound
#define bs lower_bound
//#define db(i) cout<<i<<endl;
typedef pair<ll,ll> pairs;
typedef vector<ll> vi;
typedef vector<pairs> vpair;
//find_by_order()  // order_of_key
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;
typedef tree<pair<int,int>, null_type, less<pair<int,int> >, rb_tree_tag,
tree_order_statistics_node_update> pbds;
struct compare{
  bool operator()(const pairs &a, const pairs &b)const{
    if(a.first == b.first) return a.second < b.second;
    return a.first > b.first;
  }
};

vi v[500000],link(500000),siz(500000),ind[500000];
multiset<ll>ms;
ll max_siz,min_val;

ll fin(ll x)
{
	if(link[x]==x)
		return x;
	return link[x]=fin(link[x]);
}

void connect(ll a,ll b)
{
	//cout<<"come :"<<a<<" "<<b<<endl;
	a=fin(a);
	if(link[b]!=0)
		b=fin(b);
	//cout<<"par "<<a<<" "<<b<<endl;
	if(a>b)swap(a,b);
	siz[a]+=siz[b];
	link[b]=a;
}

void solve()
{
	ll n;cin>>n;
	vi v(n);
	fr(n+1)siz[i]=1;
	rep(i,0,n)
	{
		cin>>v[i];
		ind[v[i]].pb(i+1);
	}
	sort(ALL(v));
	rep(i,0,n)
	{
		//cout<<"i:"<<i<<endl;

		if(!ms.empty())
		{
			if(*ms.begin()==(*(--ms.end())))
			{
				//cout<<"here"<<endl;
				if(max_siz<ms.size())
				{
					max_siz=ms.size();
					min_val=v[i];
				}
			}
		}
		rep(j,0,ind[v[i]].size())
		{
			ll k=ind[v[i]][j];
			//cout<<"k :"<<k<<endl;
			if(link[k-1]==0 && link[k+1]==0)
			{
				link[k]=k;
				siz[k]=1;
			}
			else
			{
				//cout<<"connecting"<<endl;
				if(link[k-1]!=0)
				{
					//cout<<"called "<<k-1<<endl;
					//cout<<"called "<<k-1<<" "<<fin(k-1)<<" "<<siz[fin(k-1)]<<" "<<ms.size()<<" "<<*ms.begin()<<endl;
					ms.erase(ms.find(siz[fin(k-1)]));
					connect(k-1,k);
				}
				if(link[k+1]!=0)
				{
					//cout<<"called "<<k+1<<" "<<fin(k+1)<<" "<<siz[fin(k+1)]<<" "<<ms.size()<<" "<<*ms.begin()<<endl;
					ms.erase(ms.find(siz[fin(k+1)]));
					connect(k+1,k);
				}
				//cout<<"connected"<<endl;
			}
			//cout<<"link[k] "<<link[k]<<endl;
			ms.is(siz[link[k]]);
			/*cout<<"siz: "<<ms.size()<<endl;
			if(!ms.empty())
			{
				multiset<ll>::iterator it=ms.begin();
				for(it;it!=ms.end();it++)
					cout<<*it<<" ";
			}
			cout<<endl<<endl;*/
		}
	}
	cout<<min_val<<endl;
}
int main()
{
	fast;
    ll t=1;
    for(int i=0;i<t;i++)
    	solve();
}


/*input
6
25 1 2 3 14 36

*/
#include<bits/stdc++.h>
#include<algorithm>
#include <fstream>
#include <sstream>
#include <string>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
using namespace __gnu_pbds;
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define is insert
#define rep1(i,a,b) for(long long i=a;i<=b;i++)
#define mp make_pair
#define mh make_heap
#define F first
#define S second
//#define fin cin
//#define fout cout
#define file ifstream fin("input.txt");ofstream fout("output.txt");
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fr(n) for(long long i=0;i<n;i++)
#define rep(i,a,b) for(long long i=a;i<b;i++)
#define ALL(x) (x).begin(), (x).end()
typedef long long int ll;
typedef long double ld;
#define lb lower_bound
#define ub uper_bound
#define bs lower_bound
//#define db(i) cout<<i<<endl;
typedef pair<ll,ll> pairs;
typedef vector<ll> vi;
typedef vector<pairs> vpair;
//find_by_order()  // order_of_key
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;
typedef tree<pair<int,int>, null_type, less<pair<int,int> >, rb_tree_tag,
tree_order_statistics_node_update> pbds;
struct compare{
  bool operator()(const pairs &a, const pairs &b)const{
    if(a.first == b.first) return a.second < b.second;
    return a.first > b.first;
  }
};

vi v[500000],link(500000),siz(500000);
map<ll,ll>ind;
multiset<ll>ms;
ll max_siz,min_val;

ll fin(ll x)
{
	if(link[x]==x)
		return x;
	return link[x]=fin(link[x]);
}

void connect(ll a,ll b)
{
	//cout<<"come :"<<a<<" "<<b<<endl;
	a=fin(a);
	if(link[b]!=0)
		b=fin(b);
	//cout<<"par "<<a<<" "<<b<<endl;
	if(a>b)swap(a,b);
	siz[a]+=siz[b];
	link[b]=a;
}

void solve()
{
	ll n;cin>>n;
	vi v(n);
	fr(n+1)siz[i]=1;
	rep(i,0,n)
	{
		cin>>v[i];
		ind[v[i]]=i+1;
	}
	sort(ALL(v));
	rep(i,0,n)
	{
		//cout<<"i:"<<i<<endl;
		if(!ms.empty())
		{
			if(*ms.begin()==(*(--ms.end())))
			{
				//cout<<"here"<<endl;
				if(max_siz<ms.size())
				{
					max_siz=ms.size();
					min_val=v[i];
				}
			}
		}
		ll k=ind[v[i]];
		//cout<<"k :"<<k<<endl;
		if(link[k-1]==0 && link[k+1]==0)
			link[k]=k;
		else
		{
			//cout<<"connecting"<<endl;
			if(link[k-1]!=0)
			{
				//cout<<"called "<<k-1<<endl;
				//cout<<"called "<<k-1<<" "<<fin(k-1)<<" "<<siz[fin(k-1)]<<" "<<ms.size()<<" "<<*ms.begin()<<endl;
				ms.erase(ms.find(siz[fin(k-1)]));
				connect(k-1,k);
			}
			if(link[k+1]!=0)
			{
				//cout<<"called "<<k+1<<" "<<fin(k+1)<<" "<<siz[fin(k+1)]<<" "<<ms.size()<<" "<<*ms.begin()<<endl;
				ms.erase(ms.find(siz[fin(k+1)]));
				connect(k+1,k);
			}
			//cout<<"connected"<<endl;
		}
		//cout<<"link[k] "<<link[k]<<endl;
		ms.is(siz[fin(k)]);
		/*cout<<"siz: "<<ms.size()<<endl;
		if(!ms.empty())
		{
			multiset<ll>::iterator it=ms.begin();
			for(it;it!=ms.end();it++)
				cout<<*it<<" ";
		}
		cout<<endl<<endl;*/
	}
	cout<<min_val<<endl;
}
int main()
{
	fast;
    ll t=1;
    for(int i=0;i<t;i++)
    	solve();
}
//10-b-0
//11-b-friction