Problem:


Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0



Sample input:
3
1 -1 2


Sample output:
4
-1 1
2 -2

Submission status: Runtime Error

Solution code:
from bisect import bisect

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

ind = bisect(A,0)

X = A[:ind]
Y = A[ind:]
ans = []
if len(X) == 0 :
    ans.append([Y[0],Y[1]])
    X.append(Y[0]-Y[1])
    Y.pop(0)
    Y.pop(0)

if len(Y) == 0 :
    if len(X) != 1 :
        ans.append([X[-1],X[-2]])
        Y.append(X[-1]-X[-2])
        X.pop(-1)
        X.pop(-1)

if len(X) + len(Y) <= 1 :
    if len(X) == 0 :
        calc = Y[0]
    else :
        calc = X[0]

while len(X) + len(Y) >= 2 :
    if len(X) >= 2 :
        ans.append([X[-1],Y[0]])
        X[-1] -= Y.pop(0)
    elif len(Y) >= 2 :
        if len(X) != 1 :
            ans.append([Y[0],X[-1]])
            Y[0] -= X.pop(-1)
        else :
            ans.append([X[-1],Y[0]])
            X[-1] -= Y.pop(0)
    else :
        calc = Y[0]-X[0]
        ans.append([Y.pop(0),X.pop(0)])

print(calc)
#print(*ans,sep="\n")
for l in ans :
    print(*l)

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush, heapify
N = int(input())
A = list(map(int, input().split()))
p = []
for i in A:
    if i > 0:
        tmp = [i, 1]
    elif i < 0:
        tmp = [-i, -1]
    else:
        N -= 1
        continue
    heappush(p, tmp)
res = []
for i in range(N-1):
    x, y = heappop(p), heappop(p)
    x = x[0] * x[1]
    y = y[0] * y[1]
    if p == []:
        if x-y > y-x:
            res.append([x,y])
            tmp = x-y
        else:
            res.append([y,x])
            tmp = y-x
        continue
    if p[0][1] > 0:
        tmp = min(x-y, y-x)
    else:
        tmp = max(x-y, y-x)
    if tmp == y-x:
        x,y=y,x
    if tmp > 0:
        tmp = [tmp, 1]
    else:
        tmp = [-tmp, -1]
    res.append([x,y])
    heappush(p, tmp)
    
print(tmp)
for i in res:
    print(*i)

Submission status: Runtime Error

Solution code:
n=int(input())
lst=[int(i) for i in input().split()]
lst.sort()
cnt=0
for i in range(n):
    if lst[i]>0:
        break
    if lst[i]<0:
        cnt+=1
ans=0
for i in lst:
    if i<0:
        ans-=i
    else:
        ans+=i
if cnt!=n and cnt!=0:
    print(ans)
    if n>2:
        for i in range(cnt+1,n):
            if i==cnt+1:
                print(lst[0],lst[i])
                res=lst[0]-lst[i]
            else:
                print(res,lst[i])
                res-=lst[i]
        if cnt>1:
            for i in range(1,cnt):
                print(res,lst[i])
                res-=lst[i]
        print(lst[cnt],res)
    else:
        print(lst[1],lst[0])
elif cnt==n:
    ans=ans+2*lst[-1]
    print(ans)
    for i in range(n-1):
        if i==0:
            print(lst[-1],lst[i])
            res=lst[-1]-lst[i]
        else:
            print(res,lst[i])
            res-=lst[i]
else:
    ans=ans-2*lst[0]
    print(ans)
    if n>2:
        for i in range(1,n-1):
            if i==1:
                print(lst[0],lst[i])
                res=lst[0]-lst[i]
            else:
                print(res-lst[i])
                res-=lst[i]
        print(lst[-1],res)
    else:
        print(lst[1],lst[0])

Submission status: Runtime Error

Solution code:
def resolve():
    N = int(input())
    As = list(map(int, input().split(" ")))
    pos = []
    neg = []
    for a in As:
        if a >= 0:
            pos.append(a)
        else:
            neg.append(a)
    pos.sort()
    neg.sort()
    x = 0
    y = 0
    ops = []
    while True:
        if len(pos) > 0 and len(neg) > 0:
            if len(pos) > len(neg):
                x = neg.pop(0)
                y = pos.pop()
            else:
                x = pos.pop()
                y = neg.pop(0)
        elif len(pos) > 1 and len(neg) == 0:
                x = pos.pop(0)
                y = pos.pop()
        elif len(neg) > 1 and len(pos) == 0:
                x = pos.pop()
                y = pos.pop(0)
        else:
            raise Exception("Unreachable?")
        
        ops.append("{} {}".format(x, y))
        xmy = x - y

        if xmy >= 0:
            pos.append(xmy)
        else:
            neg.insert(0, xmy)
        
        if len(pos + neg) == 1:
            print((pos + neg)[0])
            break
    
    [print(i) for i in ops]

if '__main__' == __name__:
    resolve()

Submission status: Runtime Error

Solution code:
n = input()
n = int(n)
num = []*n
numint = []
num = input().split(' ')
for i in range(len(num)):
    numint.append(int(num[i]))
i = 0
x, y = int, int

while len(numint) > 1:
    numint = sorted(numint)
    x = numint.pop(0)
    y = numint.pop(1)
    print(str(x) + " " + str(y))
    numint.append(x*y)
print(numint[0])

Submission status: Runtime Error

Solution code:
import numpy as np


N = int(input())

poss, negs = [], []
npos, nneg = 0, 0
for a in input().split():
    ia = int(a)
    if ia < 0:
        negs.append(ia)
        nneg += 1
    else:
        poss.append(ia)
        npos += 1

# import random
# N = 100000
# npos, nneg = 40000, 60000
# poss = [random.randint(1, 1000) for _ in range(npos)]
# negs = [random.randint(-1000, -1) for _ in range(nneg)]

if N == 2:
    a1, a2 = (poss + negs)
    if a1 < a2:
        print(a2 - a1)
        print(a2, a1)
    else:
        print(a1 - a2)
        print(a1, a2)
    exit(1)

if nneg == 0:
    print(sum(poss) - min(poss) * 2)
    argmin = np.array(poss).argmin()
    minpos = poss.pop(argmin)
    pos = poss.pop()
    print(minpos, pos)
    negs.append(minpos - pos)
    npos -= 2
    nneg += 1
elif npos == 0:
    print(-sum(negs) + max(negs) * 2)
    argmax = np.array(negs).argmax()
    maxneg = negs.pop(argmax)  # -1とか
    neg = negs.pop()  # -5とか
    print(maxneg, neg)
    poss.append(maxneg - neg)
    nneg -= 2
    npos += 1
else:
    print(sum(poss) - sum(negs))

if npos > nneg:
    for _ in range(npos - nneg):
        pos, neg = poss.pop(), negs.pop()
        print(neg, pos)
        negs.append(neg - pos)
else:
    for _ in range(nneg - npos):
        pos, neg = poss.pop(), negs.pop()
        print(pos, neg)
        poss.append(pos - neg)

for i in range(min(nneg, npos) - 1):
    pos, neg = poss.pop(), negs.pop()
    print(neg, pos)
    negs.append(neg - pos)
    pos, neg = poss.pop(), negs.pop()
    print(pos, neg)
    poss.append(pos - neg)

pos, neg = poss.pop(), negs.pop()
print(pos, neg)

Submission status: Runtime Error

Solution code:
#

import itertools
from collections import Counter
from collections import defaultdict
import bisect
from heapq import heappush, heappop
from collections import deque

def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    index = bisect.bisect_left(A, 0)
    minus = deque(A[:index])
    plus = deque(A[index:])
    # print(minus)
    # print(plus)
    progres = []
    ans = 0
    while True:
        if len(plus) == 1 and len(minus) == 1:
            p = plus.pop()
            m = minus.pop()
            progres.append((p, m))
            ans = p - m
            # print('{} {}'.format(p, m))
            break

        if len(plus) == 1 and len(minus) == 0:
            ans = plus.pop()
            break
        if len(plus) == 0 and len(minus) == 1:
            ans = minus.pop()
            break

        # まだ2つ以上入ってる
        if len(plus) == 0:
            val1 = minus.popleft()
            val2 = minus.pop()
            new_val = val1 - val2
            plus.append(new_val)
            progres.append((val1, val2))
            # print('{} {}'.format(val1, val2))
            continue

        if len(minus) == 0:
            val1 = plus.popleft()
            val2 = plus.pop()
            new_val = val1 - val2
            minus.append(new_val)
            progres.append((val1, val2))
            # print('{} {}'.format(val2, val1))
            continue

        if len(plus) > len(minus):
            val1 = plus.pop()
            val2 = minus.popleft()
            new_val = val2 - val1
            progres.append((val2, val1))

            index = bisect.bisect_left(minus, new_val)
            minus.insert(index, new_val)
            # print('{} {}'.format(val2, val1))
        else:
            val1 = plus.pop()
            val2 = minus.popleft()
            new_val = val1 - val2
            progres.append((val1, val2))

            index = bisect.bisect_left(plus, new_val)
            plus.insert(index, new_val)
            # print('{} {}'.format(val1, val2))

    print(ans)
    for p, q in progres:
        print('{} {}'.format(p, q))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush
N = int(input())
line = map(int, input().split())
h = sorted(line)
# print(h)
ans = []
M = 0

if (h[-1] < 0):
    i = 0
    temp = h[i]
    while i < N:
        i += 1
        y = h[i]
        ans += [(temp, y)]
        temp -= y
else:
    posi_num = 0
    for i in range(N):
        if (h[N-i-1] < 0):
            neg_num = N-posi_num
            break
        posi_num += 1
    else:
        posi_num -= 1
        neg_num = 1

    temp = h[0]
    i = 0
    while posi_num-1 > i:
        y = h[N-i-1]
        ans += [(temp, y)]
        temp -= y
        i += 1
    
    j = 0
    while neg_num > j:
        if (j == 0):
            x = h[neg_num]
            ans += [(x, temp)]
            temp = x - temp
        else:
            y = h[j-1]
            ans += [(temp, y)]
            temp -= y
        j += 1

print(temp)
for xy in ans:
    print(*xy)

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split(" ")))
A.sort()

n_pos = len([a for a in A if a > 0])
operations = []
if n_pos <= (N + 1) // 2:
    pos = [a for a in A if a > 0]
    neg = [a for a in A if a <= 0]
    tmp = pos[0]
    for i in range(n_pos-1):
        operations.append((neg[i], tmp))
        tmp = neg[i] - tmp
        operations.append((pos[i+1], tmp))
        tmp = pos[i+1] - tmp
        
    for i in range(n_pos-1, len(neg)):
        operations.append((tmp, neg[i]))
        tmp = tmp - neg[i]
else:
    neg = A[:N//2]
    pos = A[N//2:]
    if N % 2 == 1:
        tmp = pos[0]
        for i in range(N//2):
            operations.append((neg[i], tmp))
            tmp = neg[i] - tmp
            operations.append((pos[i+1], tmp))
            tmp = pos[i+1] - tmp
    else:
        operations.append((pos[0], neg[0]))
        tmp = pos[0] - neg[0]
        if i in range(1, N//2):
            operations.append((neg[i], tmp))
            tmp = neg[i] - tmp
            operations.append((pos[i], tmp))
            tmp = pos[i] - tmp

print(tmp)
for o in operations:
    print("{} {}".format(o[0], o[1]))

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
nega = []
for i in range(N):
    if A[0] < 0:
        nega.append(A.pop(0))
    else:
        break
N = len(A)
print( sum(A[N//2:]) - sum(A[:N//2]) - sum(nega))
B = [0]*N
l,r = 0,N-1
for i in range(N):
    if i%2 == 0:
        B[i] = A[r]
        r -= 1
    else:
        B[i] = A[l]
        l += 1
hoge = B[-1]
for i in range(N-1):
    print(B[N-i-2],hoge)
    hoge = B[N-i-2]-hoge
for i in nega:
    print(hoge,i)
    hoge -= i

Submission status: Runtime Error

Solution code:
import sys, math, collections, heapq, itertools
  
def solve():
    file = sys.stdin.readline #single: int(file()), line: map(int, file().split())
    INF = 10 ** 25
    mod = 7 + 10 ** 9
    N = int(file())
    A = [int(a) for a in file().split()]
    A.sort()
    ans = 0
    out = []
    if N == 2:
        ans = A[1] - A[0]
        out = [A[1], A[0]]
    elif A[N-2] < 0:
        ans = A[N-1] - A[N-2]
        out.append([A[N-1], A[N-2]])
        for i in reversed(range(N-2)):
            out.append([ans, A[i]])
            ans -= A[i]
    elif A[1] >= 0:
        ans = A[0] - A[1]
        out.append([A[0], A[1]])
        for i in range(2, N-1):
            out.append([ans, A[i]])
        out.append([A[N-1], ans])
        ans = A[N-1] - ans
    else:
        for i in range(1, N-1):
            if A[i] >= 0:
                start = i-1
                break
        if -A[start] <= A[start + 1]:
            ans = A[0] - A[start + 1]
            out.append([A[0], A[start + 1]])
            for i in range(start + 2, N):
                out.append([ans, A[i]])
                ans -= A[i]
            out.append([A[start], ans])
            ans = A[start] - ans
            for i in range(1, start):
                out.append([ans, A[i]])
                ans -= A[i]
        else:
            ans = A[0] - A[start + 2]
            out.append([A[0], A[start + 2]])
            for i in range(start + 3, N):
                out.append([ans, A[i]])
                ans -= A[i]
            out.append([A[start + 1], ans])
            ans = A[start + 1] - ans
            for i in range(1, start + 1):
                out.append([ans, A[i]])
                ans -= A[i] 

    print(ans)
    for k in out:
        print(" ".join(map(str, k)))

    return 0
  
if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
N = int(input())
A = [int(i) for i in input().split()]
Aplus = [int(i) for i in A if i>=0]
Amainasu = [int(i) for i in A if i<0]
Aplus.sort(reverse=True)
Amainasu.sort()
hoge = 0
result = []
res = 0
if len(Aplus) >= 1 and len(Amainasu) >= 1:
    for i in range(len(Aplus) - 1):
        result.append((Amainasu[0],Aplus[i]))
    for i in range(len(mainasu)):
        result.append((Aplus[-1],Amainasu[i]))
    res = sum(Aplus) - sum(Amainasu)
elif len(Aplus) == 0 and len(Amainasu) >= 1:
    hoge = Amainasu[-1]
    for i in range(len(Amainasu) - 1):
        result.append((hoge,Amainasu[i]))
        hoge -= Amainasu[i]
    res = sum(Amainasu) * -1 + max(Amainasu) * 2
elif len(Aplus) >= 1 and len(Amainasu) == 0:
    if len(Aplus) >= 3:
        hoge = Aplus[0]
        for i in range(len(Aplus) - 2):
            result.append((hoge,Aplus[0]))
            hoge -= Aplus[0]
            Aplus.pop(0)
            Aplus.pop(-1)
            Aplus.append(hoge)
        result.append((Aplus[0],Aplus[1]))
        res = sum(Aplus) - min(Aplus)
    else:
        result.append(Aplus[0],Aplus[1])
        res = Aplus[0] - Aplus[1]
print(res)
for i in result:
    print(str(i[0])+" "+str(i[1]))

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
N = int(input())
A = list(map(int,input().split()))
B = []

while True:
    A.sort()
    gap = A[len(A)-1]-A[0]
    mgap = abs(A[1]-A[0])
    Mgap = abs(A[len(A)-1]-A[len(A)-2])
    
    if mgap > Mgap:
        B.append([A[0],A[len(A)-1]])
        A.append(A[0]-A[len(A)-1])
        del A[0]
        del A[len(A)-2]
    else:
        B.append([A[len(A)-1],A[0]])
        A.append(A[len(A)-1]-A[0])
        del A[0]
        del A[len(A)-2]
        
    if len(A) == 2:
        print(abs(A[0]-A[1]))
        break
    
for i in B:
    print(i[0],i[1])
print(max(A),min(A))

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split(" ")))
A.sort()

n_pos = len([a for a in A if a > 0])
operations = []
if n_pos <= (N + 1) // 2:
    pos = [a for a in A if a > 0]
    neg = [a for a in A if a <= 0]
    tmp = pos[0]
    for i in range(n_pos-1):
        operations.append((neg[i], tmp))
        tmp = neg[i] - tmp
        operations.append((pos[i+1], tmp))
        tmp = pos[i+1] - tmp
        
    for i in range(n_pos-1, len(neg)):
        operations.append((tmp, neg[i]))
        tmp = tmp - neg[i]
else:
    neg = A[:N//2]
    pos = A[N//2:]
    if N % 2 == 1:
        tmp = pos[0]
        for i in range(N//2):
            operations.append((neg[i], tmp))
            tmp = neg[i] - tmp
            operations.append((pos[i+1], tmp))
            tmp = pos[i+1] - tmp
    else:
        operations.append(pos[0], neg[0])
        tmp = pos[0] - neg[0]
        if i in range(1, N//2):
            operations.append(neg[i], tmp)
            tmp = neg[i] - tmp
            operations.append(pos[i], tmp)
            tmp = pos[i] - tmp

print(tmp)
for o in operations:
    print("{} {}".format(o[0], o[1]))

Submission status: Runtime Error

Solution code:
n=int(input())
li = list(map(int,input().split()))
li.sort()
ans=[]
dekai=0
tiisai=0
for i in range(n):
    if li[i]<=0:
        tiisai+=1
    else:
        dekai=n-i
        break
while len(li)>1:
    if dekai>tiisai:
        x=li.pop(0)
        y=li.pop()
        dekai-=1
        if x==y:
            dekai-=1
            tiisai+=1
    else:
        x=li.pop()
        y=li.pop(0)
        tiisai-=1
        if x==y:
            dekai-=1
            tiisai+=1
    ans.append([x,y])
    n=x-y
    for i in range(len(li)):
        if li[i]>=n:
            li.insert(i,n)
            break
    if i==len(li):
        li.append(n)
print(li[0])
for i in range(len(ans)):
    print(ans[i][0],ans[i][1])

Submission status: Runtime Error

Solution code:
import sys

N=input()
A=map(int, sys.stdin.readline().split())
A.sort()

L=[]
for i in range(N-1):
	if i==0:
		next=A[i]-A[i+1]
		L.append( (A[i], A[i+1]) )

	else:
		if i==N-2:
			if A[i+1]<next:
				ans=next-A[i+1]
				L.append( (next,A[i+1]) )
			else:
				ans=A[i+1]-next
				L.append( (A[i+1],next) )
		else:
			L.append( (next, A[i+1]) )
			next=next-A[i+1]
else:
	print ans
	for x, y in L:
		print x,y

Submission status: Runtime Error

Solution code:
n=int(input())
xs=sorted(map(int,input().split()))
for i in range(n-2):
    if i == 0:
        a = xs[0] - xs[1]
    else:
        a = a - xs[i+1]
print(xs[-1]-a)
for i in range(n-2):
    if i == 0:
        print(xs[0],xs[1])
        a = xs[0] - xs[1]
    else:
        print(a,xs[i+1])
        a = a - xs[i+1]
print(xs[-1],a)

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int,input().split()))
s=[i for i in a if i<0]
t=sorted([i for i in a if i>0])
if len(s)==0:
    print(t[-1]-t[0]+sum(t[1:-1]))
    k=t[0]
    for i in range(1,n-1):
        print(k,t[i])
        k-=t[i]
    print(t[-1],k)
elif len(t)==0:
    d=s[0]
    print(s[0]-sum(s[1:]))
    for i in range(1,n):
        print(d,s[i])
        d-=s[i]
else:
    print(t[-1]-sum(s)+sum(t[:-1]))
    p=t[-1]
    for i in range(1,len(s)):
        print(p,s[i])
        p-=s[i]
    g=s[0]
    for i in range(len(t)-1):
        print(g,t[i])
        g-=t[i]
    print(p,g)

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    n, k = LI()
    a = n - k
    if k == 1:
        print(0)
        return
    print(a)
    return

#B
def B():
    n = II()
    xy = LIR(n)
    if n == 1:
        print(1)
        return
    ans = inf
    for i in range(n):
        for k in range(n):
            if i != k:
                b = 1
                check = []
                check.append((i,k))
                p = xy[i][0] - xy[k][0]
                q = xy[i][1] - xy[k][1]
                for l in range(n):
                    for m in range(n):
                        if not((l,m) in check) and p == xy[l][0] - xy[m][0] and q == xy[l][1] - xy[m][1]:
                            b += 1
                            check.append((l, m))
                ans = min(ans, n-b)
    print(ans)

    return

#C
def C():
    m = II()
    a = LI()
    a.sort()
    check = [0] * m
    anslis = []
    ans = 0
    if m % 2:
        ans += a[m // 2]
        for i in range(m//2):
            anslis.append((a[i], a[-1 - i]))
            anslis.append((ans,-a[-1 - i]+a[i]))
            ans += a[-1 - i] - a[i]
    else:
        ans += a[m//2] - a[m//2-1]
        for i in range(m//2-1):
            anslis.append((a[i], a[-1 - i]))
            anslis.append((ans,-a[-1 - i]+a[i]))
            ans += a[-1 - i] - a[i]
    print(ans)
    for a, b in anslis:
        print(a,b)
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    B()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys


def main():
    N = int(input())
    A = sorted(list(map(int, input().split())))
    if A[0] > 0:
        printAllPlus(A)
        sys.exit()
    elif A[N - 1] < 0:
        printAllMinus(A)
        sys.exit()

    i = -1
    for k, n in enumerate(A):
        if n >= 0:
            i = k
            break
    plus = A[i:]
    minus = A[:i]
    print(sum(plus) - sum(minus))
    while len(plus) > 1:
        p = plus.pop()
        m = minus.pop()
        print(m, p)
        minus.append(m - p)
    p0 = plus.pop()
    for m in minus:
        print(p0, m)
        p0 -= m


def printAllPlus(nums):
    ans = sum(nums) - 2 * nums[0]
    print(ans)
    tmp = nums[0]
    for n in nums[1:-1]:
        print(tmp, n)
        tmp -= n
    print(nums[-1], tmp)


def printAllMinus(nums):
    nums.reverse()
    ans = -sum(nums) + 2 * nums[0]
    print(ans)
    tmp = nums[0]
    for n in nums[1:]:
        print(tmp, n)
        tmp -= n


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
a = [int(i) for i in input().split(" ")]
b = [j for j in a if j >= 0]
m = 0
pri = []

for i in range(n-1):
    mina = min(a)
    minb = min(b)
    maxa = max(a)
    if i == n-2:
        pri.append([maxa,mina])
        m = maxa-mina
    elif mina < 0:
        pri.append([mina,minb])
        a.append(mina-minb)
        a.remove(mina)
        a.remove(minb)
        b.remove(minb)
    else:
        pri.append([mina,maxa])
        a.append(mina-maxa)
        a.remove(mina)
        a.remove(maxa)
        b.remove(minb)

print(m)
for x,y in pri:
    print(x,y)

Submission status: Runtime Error

Solution code:
# cook your dish here
n=int(input())
lst=[int(i) for i in input().split()]
lst.sort()
cnt=0
for i in range(n):
    if lst[i]>0:
        break
    if lst[i]<0:
        cnt+=1
ans=0
for i in lst:
    if i<0:
        ans-=i
    else:
        ans+=i
if cnt!=n and cnt!=0:
    print(ans)
    for i in range(cnt+1,n):
        if i==cnt+1:
            print(lst[0],lst[i])
            res=lst[0]-lst[i]
        else:
            print(res,lst[i])
            res-=lst[i]
    if cnt>1:
        for i in range(1,cnt):
            print(res,lst[i])
            res-=lst[i]
    print(lst[cnt],res)
elif cnt==n:
    ans=ans+2*lst[-1]
    print(ans)
    for i in range(n-1):
        if i==0:
            print(lst[-1],lst[i])
            res=lst[-1]-lst[i]
        else:
            print(res,lst[i])
            res-=lst[i]
else:
    ans=ans-2*lst[0]
    print(ans)
    for i in range(1,n-1):
        if i==1:
            print(lst[0],lst[i])
            res=lst[0]-lst[i]
        else:
            print(res-lst[i])
            res-=lst[i]
    print(lst[-1],res)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from bisect import bisect
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def main():
    n = int(input())
    a = [int(ai) for ai in input().split()]

    a.sort()

    o = []

    d = bisect(a, 0)
    if d == 0:
        o.append('%d %d' % (a[0], a[1]))
        a[0] -= a[1]
        del a[1]
        n -= 1
        d = 1

    s = a[d - 1]

    for i in range(d, n - 1):
        o.append('%d %d' % (s, a[i]))
        s -= a[i]

    if d != n:
        o.append('%d %d' % (a[-1], s))
        s = abs(s) + a[-1]

    if s < 0:
        o.append('%d %d' % (a[d], a[d - 1]))
        s = s[d] - a[d - 1]

    for i in range(0, d - 1):
        o.append('%d %d' % (s, a[i]))
        s += abs(a[i])

    print(s)
    print('\n'.join(o))


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n=int(input())
l=sorted(list(map(int,input().split())))
if l[0]>=0:
  c=l[0]
  l1=[]
  for i in range(1,n-1):
    l1.append([c,l[i]])
    c-=l[i]
  score=l[-1]-c
  print(score)
  for i in l1:
    print(i[0],i[1])
  print(l[-1],c)
elif l[-1]<0:
  c=l[-1]
  l1=[]
  for i in range(0,n-1):
    l1.append([c,l[i]])
    c-=l[i]
  print(c)
  for i in l1:
    print(i[0],i[1])
else:
  l1=[]
  l2=[]
  l3=[]
  for i in l:
    if i<=0:
      l1.append(i)
    else:
      l2.append(i)
  c=l1[0]
  for i in range(len(l2)-1):
    l3.append([c,l2[i]])
    c-=l2[i]
  s1=l2[len(l2)-1]
  for i in range(1,len(l1)):
    l3.append([s1,l1[i]])
    s1-=l1[i]
  score=s1-c
  print(score)
  for i in l3:
    print(i[0],i[1])
  print(s1,c)

Submission status: Runtime Error

Solution code:
import numpy as np


N = int(input())

poss, negs = [], []
npos, nneg = 0, 0
for a in input().split():
    ia = int(a)
    if ia < 0:
        negs.append(ia)
        nneg += 1
    else:
        poss.append(ia)
        npos += 1

if N == 2:
    a1, a2 = (poss + negs)
    if a1 < a2:
        print(a2 - a1)
        print(a2, a1)
    else:
        print(a1 - a2)
        print(a1, a2)
    exit(1)

if nneg == 0:
    print(sum(poss) - min(poss) * 2)
    argmin = np.array(poss).argmin()
    minpos = poss.pop(argmin)
    pos = poss.pop()
    print(minpos, pos)
    negs.append(minpos - pos)
    npos -= 2
    nneg += 1
elif npos == 0:
    print(-sum(negs) + max(negs) * 2)
    argmax = np.array(negs).argmax()
    maxneg = negs.pop(argmax)  # -1とか
    neg = negs.pop()  # -5とか
    print(maxneg, neg)
    poss.append(maxneg - neg)
    nneg -= 2
    npos += 1
else:
    print(sum(poss) - sum(negs))

if npos > nneg:
    for _ in range(npos - nneg):
        pos, neg = poss.pop(), negs.pop()
        print(neg, pos)
        negs.append(neg - pos)
else:
    for _ in range(nneg - npos):
        pos, neg = poss.pop(), negs.pop()
        print(pos, neg)
        poss.append(pos - neg)

for _ in range(nneg - 1):
    pos, neg = poss.pop(), negs.pop()
    print(neg, pos)
    negs.append(neg - pos)
    pos, neg = poss.pop(), negs.pop()
    print(pos, neg)
    poss.append(pos - neg)

pos, neg = poss.pop(), negs.pop()
print(pos, neg)

Submission status: Runtime Error

Solution code:
from collections import deque
N = int(input())
A = list(map(int, input().split()))
bb = deque(sorted(A))
x = [0]*(N-1)
y = [0]*(N-1)
start_bool = 1 if N % 2 == 0 else -1
for i in range(N-1):
    print(bb)
    l = bb.popleft()
    r = bb.pop()
    if start_bool < 0:
        if l > r:
            ret = r - l
            x[i] = r
            y[i] = l
        else:
            ret = l - r
            x[i] = l
            y[i] = r
    else:
        if l > r:
            ret = l - r
            x[i] = l
            y[i] = r
        else:
            ret = r - l
            x[i] = r
            y[i] = l
    if ret > 0:
        bb.append(ret)
    else:
        bb.appendleft(ret)
    start_bool *= -1
print(bb.pop())
for i in range(N-1):
    print(x[i], y[i])