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:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
As = list(mapint())
As.sort()
mini = As.pop(0)
maxi = As.pop()

ans = []
for a in As:
    if a>=0:
        ans.append((mini, a))
        mini -= a
    else:
        ans.append(print(maxi, a))
        maxi -= a

print(maxi-mini)
for a in ans:
    print(*a)
    print(maxi, mini)

Submission status: Runtime Error

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

A.sort()
S = sum(A)

if A[0] >= 0:
    print(S - A[0] * 2)
    tmp = A[0]
    for i in range(1, N - 1):
        print(tmp, A[i])
        tmp -= A[i]
    print(A[-1], tmp)

elif A[-1] <= 0:
    print(-S + A[-1] * 2)
    tmp = A[-1]
    for i in range(1, N):
        print(tmp, A[~i])
        tmp -= A[~i]

else:
    op = []
    tmp1 = A[-1]
    i = 1
    while A[i] < 0:
        op.append((tmp, A[i]))
        tmp1 -= A[i]
        i += 1
    tmp2 = A[0]
    i = ~1
    while A[i] >= 0:
        op.append((tmp2, A[~i]))
        tmp2 -= A[~i]
        i -= 1
    print(tmp1 - tmp2)
    for x, y in op:
        print(x, y)
        print(tmp1, tmp2)

Submission status: Runtime Error

Solution code:
n,*a=map(int,open(0).read().split())
a.sort()
print(sum(abs(i)for i in a)-2*abs(a[0]))
if n==2:
    print(a[1]-1[0])
    print(a[1],a[0])
else:
    print(a[0],a[-1])
    a[0]-=a[-1]
    for i in a[1:-2]:
        print(a[0],i)
        a[0]-=i
    print(a[-2],a[0])

Submission status: Runtime Error

Solution code:
n,*a=map(int,open(0).read().split())
a.sort()
p,z,m=[],[],[]
for i in a:
    if i<0:m+=[i]
    elif i>0:p+=[i]
    else:z+=[i]
if p and m:
    p=z+p
    for i in p[:-1]:
        # print(m[0],i)
        m[0]-=i
    for i in m:
        # print(p[-1],i)
        p[-1]-=i
    print(p[-1])    
elif p:
    p=z+p
    for i in p[:-2]:
        # print(p[0],i)
        p[0]-=i
    print(p[-2]-p[0])    
elif m:
    m=m+z
    for i in p[:-1]:
        # print(p[-1],i)
        p[-1]-=i
    print(p[-1])    
if p and m:
    p=z+p
    for i in p[:-1]:
        print(m[0],i)
        m[0]-=i
    for i in m:
        print(p[-1],i)
        p[-1]-=i
elif p:
    p=z+p
    for i in p[:-2]:
        print(p[0],i)
        p[0]-=i
    print(p[-2],p[0])    
elif m:
    m=m+z
    for i in p[:-1]:
        print(p[-1],i)
        p[-1]-=i

Submission status: Runtime Error

Solution code:
if p and m:
    p=z+p
    for i in p[:-1]:
        print(m[0],i)
        m[0]-=i
    for i in m:
        print(p[-1],i)
        p[-1]-=i
elif p:
    p=z+p
    for i in p[:-2]:
        print(p[0],i)
        p[0]-=i
    print(p[-2],p[0])    
elif m:
    m=m+z
    for i in p[:-1]:
        print(p[-1],i)
        p[-1]-=i

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N = in_n()
    A = in_nl()

    pa, ma = [], []
    for i in range(N):
        if A[i] >= 0:
            pa.append(A[i])
        else:
            ma.append(A[i])

    pa = deque(sorted(pa))
    ma = deque(sorted(ma))

    max_value = 0
    ans = []
    while pa or ma:

        if len(pa) >= 1 and len(ma) >= 1:
            if len(pa) == 1 and len(ma) == 1:
                p, m = pa.popleft(), ma.popleft()
                ans.append((p, m))
                max_value = p - m
            elif len(pa) >= 2 and len(ma) >= 1:
                p, m = pa.popleft(), ma[0]
                ans.append((m, p))
                ma[0] -= p
            elif len(pa) >= 1 and len(ma) >= 2:
                p, m = p[0], ma.popleft()
                ans.append((p, m))
                pa[0] -= m
        elif len(pa) >= 2:
            if len(pa) == 2:
                p1, p2 = pa.popleft(), pa.popleft()
                p1, p2 = max(p1, p2), min(p1, p2)
                ans.append((p1, p2))
                max_value = p1 - p2
            else:
                p1, p2 = pa.popleft(), pa.popleft()
                ans.append((p1, p2))
                if (tp := p1 - p2) >= 0:
                    pa.appendleft(tp)
                else:
                    ma.append(tp)
        elif len(ma) >= 2:
            if len(ma) == 2:
                m1, m2 = ma.popleft(), ma.popleft()
                m1, m2 = max(m1, m2), min(m1, m2)
                ans.append((m1, m2))
                max_value = m1 - m2
            else:
                m1, m2 = ma.popleft(), ma.popleft()
                ans.append((m1, m2))
                pa.appendleft(m1 - m2)

    print(max_value)
    print('\n'.join(map(lambda a: '{} {}'.format(a[0], a[1]), ans)))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import deque
from bisect import bisect_left

N = int(input())
a = list(map(int, input().split()))
a.sort()
zloc = bisect_left(a, 0)
pos =a[zloc:] 
neg =a[:zloc]
pn=len(pos)
nn=len(neg)

dif = pn-nn

pq = deque(pos)
nq = deque(neg)
c = 0
ans = [" "]*(N-1)
rep=N-1

while dif > 1:
  n = nq.pop()
  p = pq.pop()
  ans[c]=str(n)+" "+str(p)
  nq.append(n-p)
  dif-=1
  c+=1
  rep-=1

if dif == 1:
  for i in range(rep):
    n = nq.pop()
    p = pq.pop()
    if i % 2==0:
      ans[c]=str(n)+" "+str(p)
      nq.append(n-p)
    else:
      ans[c]=str(p)+" "+str(n)
      pq.append(p-n)
    c+=1
  print(pq.pop())

while dif < -1:
  n = nq.pop()
  p = pq.pop()
  ans[c]=str(p)+" "+str(n)
  pq.append(p-n)
  dif+=1
  c+=1
  rep-=1 

if dif == -1 or dif == 0 :
  for i in range(rep):
    n = nq.pop()
    p = pq.pop()
    if i%2==0 or i == rep-1:
      ans[c]=str(p)+" "+str(n)
      pq.append(p-n)
    elif i % 2==1:
      ans[c]=str(n)+" "+str(p)
      nq.append(n-p)
    c+=1
  print(pq.pop())
for j in range(N-1):
  print(ans[j])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)


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


def resolve():
    n = int(input())
    A = sorted(list(map(int, input().split())))

    if n==2:
        print(A[1]-A[0])
        print(A[1],A[0])
    else:
        val = -A[0]
        fl = False
        for i in range(1, n):
            if A[i] < 0:
                val -= A[i]
            else:
                val += A[i]
                if not fl:
                    border = i
                    fl = True

        print(val)

        org_val = A[0]
        i = 1
        while border+i < n:
            print(org_val,A[border+i])
            org_val -= A[border+i]
            i += 1


        print(A[border], org_val)
        org_val = A[border]-org_val

        for i in range(1, border):
            print(org_val, A[i])
            org_val -= A[i]

resolve()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)


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


def resolve():
    n = int(input())
    A = sorted(list(map(int, input().split())))

    val = -A[0]
    fl = False
    for i in range(1, n):
        if A[i] < 0:
            val -= A[i]
        else:
            val += A[i]
            if not fl:
                border = i
                fl = True

    print(val)

    org_val = A[0]
    i = 1
    while border+i < n:
        print(org_val,A[border+i])
        org_val -= A[border+i]
        i += 1


    print(A[border], org_val)
    org_val = A[border]-org_val

    for i in range(1, border):
        print(org_val, A[i])
        org_val -= A[i]

resolve()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))

N = ini()
A = inl()
A.sort()


def solve():
    i = N - 1
    j = 0
    big = A[i]
    small = A[j]
    i -= 1
    j += 1
    res = []
    while i <= j:
        if i == j:
            res.append((small, A[i]))
            small -= A[i]
            break
        res.append((big, A[j]))
        big -= A[j]
        res.append((small, A[i]))
        small -= A[i]
        i -= 1
        j += 1

    print(big - small)
    for x, y in res:
        print(x, y)
    print(big, small)


solve()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))

N = ini()
A = inl()
A.sort()


def solve():
    i = N - 1
    j = 0
    big = A[i]
    small = A[j]
    i -= 1
    j += 1
    res = []
    while i <= j:
        if i == j:
            small -= A[i]
            res.append((small, A[i]))
            break
        big -= A[j]
        res.append((big, A[j]))
        small -= A[i]
        res.append((small, A[i]))
        i -= 1
        j += 1

    print(big - small)
    for x, y in res:
        print(x, y)


solve()

Submission status: Runtime Error

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    a = [(abs(int(i)),int(i)) for i in ipt().split()]
    a.sort()
    if a[2][1] > 0:
        op = [(a[0][1],a[1][1])]
        ans = a[0][1]-a[1][1]
    else:
        ans = a[1][1]-a[0][1]
        op = [(a[1][1],a[0][1])]
    for i,ai in enumerate(a[2:n-1:]):
        if a[i+3][1] > 0:
            op.append((min(ans,ai[1]),max(ans,ai[1])))
            ans = min(ans,ai[1])-max(ans,ai[1])
        else:
            op.append((max(ans,ai[1]),min(ans,ai[1])))
            ans = max(ans,ai[1])-min(ans,ai[1])
    op.append((max(ans,a[n-1][1]),min(ans,a[n-1][1])))
    ans = max(ans,a[n-1][1])-min(ans,a[n-1][1])
    print(ans)
    for x,y in op:
        print(x,y)
    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)


    def solve(L):
        M = 0
        command = []
        if L[-1] >= 0:
            # 全て正
            command.append([L[-1], L[0]])
            neg = L[-1] - L[0]
            L = L[1:-1]
            for i in range(1, len(L)):
                command.append([neg, L[i]])
                neg -= L[i]
            # 最後に正 - 負
            command.append([L[0], neg])
            M = L[0] - neg
        elif L[0] <= 0:
            # 全て負
            command.append([L[0], L[-1]])
            pos = L[0] - L[-1]            
            L = L[1:-1]
            for i in range(len(L)):
                command.append([pos, L[i]])
                pos -= L[i]
            M = pos
        else:
            for i in range(len(L)):
                if L[i] < 0:
                    break
            neg = L[i]
            for j in range(1, i):
                command.append([neg, L[j]])
                neg -= L[j]
            L = [L[0], neg] + L[i+1:]
            M = L[0]
            for i in range(1, len(L)):
                command.append([M, L[i]])
                M -= L[i]
        return M, command
                

    
    
    n = ii()
    L = lmi()
    L.sort(reverse=True)
    M, command = solve(L)
    print(M)
    for x, y in command:
        print(f"{x} {y}")


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int,input().split()))

a.sort()

u,d,z = 0,0,0
uu,dd = [],[]
for i in range(n):
    if a[i] > 0:
        u += 1
        uu.append(a[i])
    elif a[i] < 0:
        d += 1
        dd.append(a[i])
    else:
        z += 1
        
dd = dd[::-1]
        
ans = []
if u == 0 and d == 0:
    for i in range(z):
        ans.append((0,0))
    cur = 0
    
elif d == 0:
    if z != 0:
        for i in range(z-1):
            ans.append((0,0))
        cur = 0
        for i in range(u-1):
            ans.append((cur,uu[i]))
            cur -= uu[i]
        ans.append((uu[u-1],cur))
        cur = uu[u-1] - cur
    else:
        cur = uu[0]
        for i in range(u-2):
            ans.append((cur,uu[i+1]))
            cur -= uu[i+1]
        ans.append((uu[u-1],cur))
        cur = uu[u-1] - cur
        
elif u == 0:
    if z != 0:
        for i in range(z-1):
            ans.append((0,0))
        cur = 0
        for i in range(d):
            ans.append((cur,dd[i]))
            cur -= dd[i]
    
    else:
        dd = d[::-1]
        cur = dd[0]
        for i in range(u-1):
            ans.append((cur,uu[i+1]))
            cur -= uu[i+1]
            
else:
    for i in range(z):
        ans.append((uu[0],0))
    cur1 = uu[0]
    cur2 = dd[0]
    for i in range(d-1):
        ans.append((cur1,dd[i+1]))
        cur1 -= dd[i+1]
    for i in range(u-1):
        ans.append((cur2,uu[i+1]))
        cur2 -= uu[i+1]
        
    ans.append((cur1,cur2))
    cur = cur1 - cur2
    
print(cur)
for i in ans:
    print(*i)

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int,input().split()))

a.sort()

u,d,z = 0,0,0
uu,dd = [],[]
for i in range(n):
    if a[i] > 0:
        u += 1
        uu.append(a[i])
    elif a[i] < 0:
        d += 1
        dd.append(a[i])
    else:
        z += 1
        
dd = dd[::-1]
        
ans = []
if d == 0:
    if z != 0:
        for i in range(z-1):
            ans.append((0,0))
        cur = 0
        for i in range(u-1):
            ans.append((cur,uu[i]))
            cur -= uu[i]
        ans.append((uu[u-1],cur))
        cur = uu[u-1] - cur
    else:
        cur = uu[0]
        for i in range(u-2):
            ans.append((cur,uu[i+1]))
            cur -= uu[i+1]
        ans.append((uu[u-1],cur))
        cur = uu[u-1] - cur
        
elif u == 0:
    if z != 0:
        for i in range(z-1):
            ans.append((0,0))
        cur = 0
        for i in range(d):
            ans.append((cur,dd[i]))
            cur -= dd[i]
    
    else:
        dd = d[::-1]
        cur = dd[0]
        for i in range(u-1):
            ans.append((cur,uu[i+1]))
            cur -= uu[i+1]
            
else:
    for i in range(z):
        ans.append((uu[0],0))
    cur1 = uu[0]
    cur2 = dd[0]
    for i in range(d-1):
        ans.append((cur1,dd[i+1]))
        cur1 -= dd[i+1]
    for i in range(u-1):
        ans.append((cur2,uu[i+1]))
        cur2 -= uu[i+1]
        
    ans.append((cur1,cur2))
    cur = cur1 - cur2
    
print(cur)
for i in ans:
    print(*i)

Submission status: Runtime Error

Solution code:
n=int(input())
p,m=[],[]
z=0
for i in list(map(int,input().split())):
    if i<0:m.append(i)
    elif i==0:
        z+=1
    else:p.append(i)
if p and m:
    print(sum(p)-sum(m))
    if z:
        for h in range(z-1):
            print("0 0")
        now=0
    else:now=p.pop()
    for j in m[1:]:
        print(now,j)
        now-=j
    print(m[0],now)
    now=-now+m[0]
    for j in p[1:]:
        print(now,j)
        now-=j
    print(p[0],now)
elif p:
    if z:
        print(sum(p))
        for h in  range(z-1):
            print("0 0")
        now=0
        f=p.pop()
        for i in p:
            print(now,i)
            now-=i
        print(f,now)
    else:
        print(sum(p)-2*min(p))
        p.sort()
        now=p[0]
        k=p.pop()
        for j in p[1:]:
            print(now,j)
            now-=j
        print(k,now)
else:
    if z:
        print(-sum(m))
        for h in  range(z-1):
            print("0 0")
        now=0
    else:
        m.sort()
        print(-sum(m)+2*max(m))
        now=m.pop()
    for i in p:
        print(now,i)
        now-=i

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int,input().split()))
a.sort()
aminus = []
aplus = []
p = 0
q = 0
for i in a:
    if i >= 0:
        aplus.append(i)
        p += 1
    elif i < 0:
        aminus.append(i)
        q += 1
ans = []
cou = 0
if aplus and aminus:
    now = aminus[0]
    for i in range(p-1):
        ans.append((now,aplus[i]))
        now = now - aplus[i]
    aminus[0] = now
    now = aplus[p-1]
    for i in range(q):
        ans.append((now,aminus[i]))
        now = now - aminus[i]
    cou = now
elif aplus:
    now = aplus[0]
    for i in range(1,p-1):
        ans.append((now,aplus[i]))
        now = now - aplus[i]
    ans.append((aplus[p-1],now))
    cou = aplus[p-1] - now
elif aminus:
    now = aminus[q-1]
    for i in range(q-1):
        ans.append(now,aminus[i])
        now = now - aminus[i]
    cou = now
print(cou)
for i in range(n-1):
    print(*ans[i])

Submission status: Runtime Error

Solution code:
n = int(input())
al = list(map(int, input().split()))
al.sort()

res = []
neg = []
pos = []
for a in al:
    if a>=0:
        pos.append(a)
    else:
        neg.append(a)

if len(pos)==0:
    res.append((neg[0],neg[1]))
    pos.append(neg[0]-neg[1])
    neg = neg[2:]
if len(neg)==0:
    res.append((pos[0],pos[1]))
    neg.append(pos[0]-pos[1])
    pos = pos[2:]


# len(pos)>0 and len(neg)>0
n = neg[0]
for i in range(1,len(pos)):
    res.append((n,pos[i]))
    n = n - pos[i]
p = pos[0]
for i in range(1,len(neg)):
    res.append((p,neg[i]))
    p = p - neg[i]
res.append((p,n))
print(p-n)
for x,y in res:
    print(x,y)

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int, input().split()))
arrays = []
a.sort()

b = []
c = []

for i in a:
    if i < 0:
        c.append(i)
    else:
        b.append(i)

if len(c) >= 1:
    while len(b) > 1:
        x = b.pop(0)
        array = [c[0], x]
        c[0] -= x
        arrays.append(array)
    while len(c) > 1:
        y = c.pop(0)
        array = [b[0], y]
        b[0] -= y
        arrays.append(array)

    array = [b[0], c[0]]
    arrays.append(array)

    print(b[0] - c[0])

else:
    mi = b.pop(0)
    while len(b) > 1:
        x = b.pop(0)
        array = [mi, x]
        mi -= x
        arrays.append(array)
    array = [b[0], mi]
    arrays.append(array)
    print(b[0]-mi)


for x, y in arrays:
    print(x, y)

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int, input().split()))
arrays = []
a.sort()

b = []
c = []

for i in a:
    if i < 0:
        c.append(i)
    else:
        b.append(i)

if len(c) >= 1:
    while len(b) > 1:
        x = b.pop(0)
        array = [c[0], x]
        c[0] -= x
        arrays.append(array)

    array = [b[0], c[0]]
    arrays.append(array)

    print(b[0] - c[0])

else:
    mi = b.pop(0)
    while len(b) > 1:
        x = b.pop(0)
        array = [mi, x]
        mi -= x
        arrays.append(array)
    array = [b[0], mi]
    arrays.append(array)
    print(b[0]-mi)


for x, y in arrays:
    print(x, y)

Submission status: Runtime Error

Solution code:
# C - Successive Subtraction

N = int(input())
A = list(int(a) for a in input().split())

M = []
P = []
for a in A:
    if a >= 0:
        P.append(a)
    else:
        M.append(a)

P.sort(reverse=True)
M.sort()
lenP = len(P)
lenM = len(M)    

ans = []
anssum = 0

if lenM ==0:
    ans.append((P[-1], P[-2]))
    tmp = P.pop() - P.pop()
    M.append(tmp)
    lenP -= 2
elif lenP ==0:
    ans.append((M[-1], M[-2]))
    tmp = M.pop() - M.pop()
    P.append(tmp)
    lenP += 1
for i in range(lenP-1):
    ans.append((M[-1], P[-1]))
    tmp = M.pop() - P.pop()
    M.append(tmp)
while M != []:
    ans.append((P[-1], M[-1]))
    tmp = P.pop() - M.pop()
    P.append(tmp)
anssum = P.pop()

print(anssum)
for i in range(len(ans)):
    print(' '.join(map(str, ans[i])))

Submission status: Runtime Error

Solution code:
from collections import deque
import bisect

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

    plus = []; minus = []
    for a in A:
        if a > 0:
            plus.append(a)
        if a < 0:
            minus.append(a)
    
        
    plus.sort()
    minus.sort()
    plus = deque(plus)
    minus = deque(minus)
    anslist = []
    if len(plus) == 0:
        stmp = minus.popleft()
        ltmp = minus.pop()
        anslist.append((ltmp, stmp))
        plus.append(ltmp-stmp)
        N -= 1
    elif len(minus) == 0:
        stmp = plus.popleft()
        ltmp = plus.pop()
        anslist.append((stmp, ltmp))
        minus.append(stmp-ltmp)
        N -= 1
    else:
        pass

    for _ in range(N):
        if len(minus) > 1:
            ltmp = plus.pop()
            stmp = minus.pop()
            anslist.append((ltmp, stmp))
            plus.append(ltmp - stmp)
        elif len(plus) > 1:
            ltmp = plus.popleft()
            stmp = minus.popleft()
            anslist.append((stmp, ltmp))
            minus.append(stmp - ltmp)
        else:
            ltmp = plus.popleft()
            stmp = minus.popleft()
            anslist.append((ltmp, stmp))
            ans = ltmp - stmp
            break
    print(ans)
    for s in anslist:
        print(*s)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from bisect import bisect_right

n = int(readline())
a = list(map(int, readline().split()))
a.sort()
if a[0] <= 0 and a[-1] >= 0:
    print(sum(map(lambda x: abs(int(x)), a)))
    idx = bisect_right(a, 0)
    x = a[0]
    y = a[idx]
    for aa in a[1:idx]:
        print(y, aa)
        y -= aa
    for aa in a[idx + 1:]:
        print(x, aa)
        x -= aa
    print(y, x)
else:
    if a[0] < 0:
        print(-sum(a) + 2 * a[-1])
        a = a[::-1]
    else:
        print(sum(a) - 2 * a[0])
    x = a[0]
    y = a[-1]
    for aa in a[1:-1]:
        print(x, aa)
        x -= aa
    if a[0] < 0:
        y, x = x, y
    print(y, x)

Submission status: Runtime Error

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import deque
def main():
    n=int(input())
    A=list(map(int,input().split()))
    A.sort(reverse=True)
    Large=deque(A)
    Small=deque()
    while len(Large)>=2:
        if Large[-1]>=0:break
        Small.append(Large.pop())
    if not Small:Small.append(Large.pop())
    ans=[]
    while len(Large)>=2:
        a=Large.pop()
        b=Small.pop()
        ans.append((b,a))
        Small.append(b-a)  
    large=Large.pop()
    while len(Small)>=2:
        b=Small.popleft()
        ans.append((b,a))
        large+=-b
    small=Small.pop()
    ans.append((large,small))
    print(large-small)
    for a,b in ans:
        print(a,b)

if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import copy
from collections import deque

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


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


def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()

    if A[0] >= 0:
        ans = sum(A[1:]) - A[0]
        plus = copy.deepcopy(A[1:])
        minus = [A[0]]
    elif A[-1] <= 0:
        ans = -sum(A[:-1]) + A[-1]
        plus = [A[-1]]
        minus = copy.deepcopy(A[:-1])
    else:
        plus = []
        minus = []
        ans = 0
        for a in A:
            if a >= 0:
                ans += a
                plus.append(a)
            else:
                ans -= a
                minus.append(a)

    plus = deque(plus)
    minus = deque(minus)
    print(ans)

    # minusをまず一つにする
    while len(minus) > 1:
        p = plus.pop()
        m = minus.pop()
        print(p, m)
        plus.append(p - m)

    # minusが1つになったあとの処理
    p = plus.pop()
    m = minus.pop()
    print(m, p)
    cur = m - p
    while len(plus) > 1:
        p = plus.pop()
        print(cur, p)
        cur -= p
    p = plus.pop()
    print(p, cur)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
# 最も小さい数から最も大きい数を引く、を繰り返すことで、できるだけ小さい数が作れる
# 最後に残った数からできるだけ小さい数を引くことで答えが求められる

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

if N==2:
  print(A[1]-A[0])

from collections import deque
q = deque(A)

seq = []
x = q.popleft()
y = q.pop()
seq += [[x,y]]
x = x-y
while len(q) > 1:
  y = q.pop()
  seq += [[x,y]]
  x = x-y

y = q.pop()
seq += [[y,x]]
print(y - x)
for s in seq:
  print(*s)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

def main():
    N = int(input())
    A = list(map(int,input().split()))
    A.sort()

    li = []
    mm1 = A[N-1]
    mm2 = A[0]
    i = 1
    
    while(i<N-1):
        if A[i]<=0:
            li.append([mm1,A[i]])
            mm1 -= A[i]
        else:
            li.append([mm2,A[i]])
            mm2 -= A[i]
        i += 1
        li.append([mm1,mm2])
    print(mm1-mm2)
    for i in range(N-1):
        print(*li[i])

        


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int , input().split()))
pos = sorted([i for i in a if i >= 0], reverse=True)
neg = sorted([i for i in a if i < 0], reverse=True)

ans = []
if len(neg) == 0 and len(pos) == 2:
    print(pos[0] - pos[1])
    print(pos[0], pos[1])
    exit()
elif len(pos) == 0:
    tmp = neg[0]
    neg = neg[1:]
    neg.append(tmp)
elif len(neg) == 0:
    neg.append(pos.pop())

tmp = neg.pop()
while len(pos) > 1:
    a = pos.pop()
    ans.append([tmp, a])
    tmp -= a
neg.append(tmp)

tmp = pos[0]
for i in neg:
    ans.append([tmp, i])
    tmp -= i

print(tmp)
[print(*i) for i in ans]