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

Solution (Python):
from collections import deque
def solve1():
    print(sum(A)-min(A)*2)
    que=deque(A)
    while(len(que)>1):
        l,r=que.popleft(),que.pop()
        if que or (not que and l-r>=r-l):
            print(l,r)
            m=l-r
            que.appendleft(m)
        else:
            print(r,l)
def solve2():
    li=list(map(abs,A))
    print(sum(li)-min(li)*2)
    que=deque(A)
    while(len(que)>1):
        l,r=que.popleft(),que.pop()
        if que or (not que and r-l>=l-r):
            print(r,l)
            m=r-l
        else:
            print(l,r)
        que.append(m)
def solve3():
    li=list(map(abs,A))
    print(sum(li))
    minus,plus=[],[]
    for i in range(N):
        if A[i]>=0:
            plus.append(A[i])
        else:
            minus.append(A[i])
    mque,pque=deque(sorted(minus)),deque(sorted(plus))
    for i in range(N-1):
        m,p=mque.pop(),pque.pop()
        if i==N-2:
            print(p,m)
        else:
            if len(mque)==0:
                print(m,p)
                mque.append(m-p)
            else:
                print(p,m)
                pque.append(p-m)
N=int(input())
A=sorted(map(int,input().split()))

if min(A)>=0:
    solve1()
elif max(A)<=0:
    solve2()
else:
    solve3()

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
a.sort()
x, y = a[0], a[-1]
w, z = a[0], a[-1]
for i in a[1:-1]:
    if i < 0:
        y -= i
    else:
        x -= i
print(y - x)
for i in a[1:-1]:
    if i < 0:
        print(z, i)
        z -= i
    else:
        print(w, i)
        w -= i
print(z, w)

Solution (Python):
import sys
from bisect import bisect_left

input = sys.stdin.readline


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

    A.sort()
    idx = bisect_left(A[1:-1], 0)
    m_group = A[1:1 + idx]
    p_group = A[1 + idx: -1]

    ans = []

    MAX = A[-1]
    for m in m_group:
        ans.append(f"{MAX} {m}")
        MAX -= m

    MIN = A[0]
    for p in p_group:
        ans.append(f"{MIN} {p}")
        MIN -= p

    ans.append(f"{MAX} {MIN}")
    M = MAX - MIN

    print(M)
    print("\n".join(ans))


if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
cnt_m = len(list(filter(lambda x: x < 0, a)))

if cnt_m == 0:
    i_m = a.index(min(a))
    i_p = (i_m + 1) % n
elif cnt_m == n:
    i_p = a.index(max(a))
    i_m = (i_p + 1) % n
else:
    i_m = i_p = -1
    for i in range(n):
        if i_m == -1 and a[i] < 0:
            i_m = i
        if i_p == -1 and a[i] >= 0:
            i_p = i

is_used = [False] * n
ans = []

is_used[i_m] = True
is_used[i_p] = True
s_m = a[i_m]
s_p = a[i_p]
for i in range(n):
    if not is_used[i]:
        if a[i] >= 0:
            ans.append((s_m, a[i]))
            s_m -= a[i]
        else:
            ans.append((s_p, a[i]))
            s_p -= a[i]

        is_used[i] = True

ans.append((s_p, s_m))
ans_s = s_p - s_m

print(ans_s)
for ans_i in ans:
    print(*ans_i)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7


N = INT()
A = LIST()

A.sort()

ans = []
if N-1 <= bisect(A, 0):
	tmp = A[-1]
	for i in range(2, N+1):
		ans.append((tmp, A[-i]))
		tmp -= A[-i]
else:
	idx = max(0, bisect(A, 0)-1)
	tmp = A[idx]
	for i in range(idx+1, N-1):
		ans.append((tmp, A[i]))
		tmp -= A[i]

	ans.append((A[-1], tmp))
	tmp = A[-1] - tmp

	for i in range(idx-1, -1, -1):
		ans.append((tmp, A[i]))
		tmp -= A[i]

print(tmp)
for x in ans:
	print(*x)

Solution (Python):
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
a.sort()
ans = []
if min(a)>=0:
    print(sum(a)-2*a[0])
    now = a[0]
    for i in range(n-2):
        print(now, a[i+1])
        now -= a[i+1]
    print(a[-1], now)
elif max(a)<=0:
    print(-sum(a)+2*a[-1])
    now = a[-1]
    for i in range(n-1):
        print(now, a[i])
        now -= a[i]
else:
    idx = bisect_left(a, 0)
    pa = a[idx:]
    na = a[:idx]
    print(sum(pa)-sum(na))
    now = pa[0]
    for i in range(len(na)-1):
        print(now, na[i])
        now -= na[i]
    pa.append(now)
    now = na[-1]
    for i in range(1, len(pa)-1):
        print(now, pa[i])
        now -= pa[i]
    print(pa[-1], now)

Solution (Python):
n=int(input())

a = list(map(int,input().split()))

a.sort()

query = []

high = a[-1]

low = a[0]

for i in range(1,n-1):
    if a[i] > 0:
        query.append([low, a[i]])
        low -= a[i]
    else:
        query.append([high, a[i]])
        high -= a[i]

query.append([high, low])

print(high-low)

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

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

ans = []
a.sort()
low = a[0]
high = a[-1]
for i in a[1:-1]:
    if i>0:
        ans.append([low,i])
        low = low - i
    else:
        ans.append([high,i])
        high = high - i

ans.append([high,low])
print(high-low)
for x,y in ans:
    print('{0} {1}'.format(x,y))

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7





M = getN()
A = getList()
plus = []
minus = []
for i in A:
    if i >= 0:
        plus.append(i)
    else:
        minus.append(i)
plus.sort()
minus.sort(reverse = True)

if len(minus) == 0:
    print(sum(plus) - 2 * min(plus))
    now = plus[0]
    for i in range(1, M - 1):
        print(now, plus[i])
        now = now - plus[i]
    print(plus[M - 1], now)
    exit()

if len(plus) == 0:
    print(-sum(minus) + 2 * max(minus))
    now = minus[0]
    for i in range(1, M):
        print(now, minus[i])
        now = now - minus[i]
    exit()

print(sum(plus) - sum(minus))
now = minus[0]
for i in range(1, len(plus)):
    print(now, plus[i])
    now = now - plus[i]

print(plus[0], now)
now = plus[0] - now

for i in range(1, len(minus)):
    print(now, minus[i])
    now = now - minus[i]

Solution (Python):
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)[::-1])

    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 = pa[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()

Solution (Python):

from collections import deque
N=int(input())
A=list(map(int, input().split()))


plus=[]
minus=[]
zeros=[]
for a in A:
    if a==0:
        zeros.append(a)
    elif a>=1:
        plus.append(a)
    else:
        minus.append(a)
plus=sorted(plus)
minus=sorted(minus)
zeros=sorted(zeros)
ans=[]
if plus and minus:
    while len(plus)>1:
        now=plus.pop()
        ans.append((minus[0],now))
        minus[0]-=now
    while len(zeros)>0:
        now=zeros.pop()
        ans.append((plus[0],now))
    while len(minus)>1:
        now=minus.pop()
        ans.append((plus[0],now))
        plus[0]-=now
    ans.append((plus[0],minus[0]))
    ansnum=plus[0]-minus[0]
else:
    ansnum=0
    if len(plus)==0:
        if zeros:
            core=zeros.pop()
        else:
            core=minus.pop()
        while len(minus)>0:
            now=minus.pop()
            ans.append((core,now))
            core-=now
        ansnum=core
    else:
        if zeros:
            core=zeros.pop()
        else:
            plus=deque(plus)
            core=plus.popleft()
        while len(plus)>1:
            now=plus.pop()
            ans.append((core,now))
            core-=now
        ans.append((plus[0],core))
        ansnum=plus[0]-core
        core=ansnum
    while len(zeros)>0:
        now=zeros.pop()
        ans.append((core,now))
    
    

print(ansnum)
for t in ans:
    x,y=t
    print(x,y)

Solution (Python):



def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    s = A[0]
    l = A[-1]
    ret = []
    for a in A[1:N-1]:
        if a>=0:
            ret.append((s, a))
            s -= a
        else:
            ret.append((l, a))
            l -= a
    print(l-s)
    ret.append((l,s))
    for x, y in ret:
        print(x, y)

if __name__ == '__main__':
    main()

Solution (Python):




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

ans = []
low = A[0]
high = A[-1]

for a in A[1:-1]:
    if a > 0:
        ans.append((low, a))
        low = low - a
    else:
        ans.append((high, a))
        high = high - a

ans.append((high, low))

print(high - low)
for (x, y) in ans:
    print(x, y)

Solution (Python):
def main():
    N = int(input())
    A = list(map(int, input().split(' ')))
    
    
    
    
    
    
    
    neg_cnt = sum([1 for a in A if a < 0])
    M = 0
    proc = list()
    if neg_cnt == N:
        
        A.sort(reverse=True)
        x = A[0]
        for y in A[1:]:
            proc.append((x, y))
            x -= y
        M = x
    elif neg_cnt == 0:
        
        A.sort()
        x = A[0]
        for y in A[1:-1]:
            proc.append((x, y))
            x -= y
        x, y = A[-1], x
        proc.append((x, y))
        M = x - y
    else:
        
        A.sort()
        x = A[-1]
        for y in A[:neg_cnt-1]:
            proc.append((x, y))
            x -= y
        former = x
        x = A[neg_cnt-1]  
        for y in A[neg_cnt:-1]:
            proc.append((x, y))
            x -= y
        latter = x
        proc.append((former, latter))
        M = former - latter
    print(M)
    for p in proc:
        x, y = p
        print('{} {}'.format(x, y))


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    if all([a > 0 for a in A]):
        pre = A[0]
        M = sum(A) - 2 * min(A)
        print(M)
        for i in range(1,N):
            if i != N - 1:
                print(pre, A[i])
                pre -= A[i]
            else:
                print(A[i], pre)
    elif all([a < 0 for a in A]):
        M = A[-1]
        for i in range(N-1):
            M -= A[i]
        print(M)
        pre = A[-1]
        for i in range(N-1):
            print(pre, A[i])
            pre -= A[i]
    else:
        cnt = 0
        M = 0
        for a in A:
            if a > 0:
                cnt += 1
            M += abs(a)
        print(M)
        if cnt == 1:
            pre = A[-1]
            for i in range(N-1):
                print(pre, A[i])
                pre -= A[i]
        else:
            pre = A[0]
            for i in range(1,N-1):
                if A[i] >= 0:
                    print(pre, A[i])
                    pre -= A[i]

            print(A[-1],pre)
            pre = A[-1] - pre
            for i in range(1,N-1):
                if A[i] < 0:
                    print(pre, A[i])
                    pre -= A[i]
                else:
                    break
                

if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
a = [int(i) for i in input().split()]
pos = [i for i in a if i >= 0]
neg = [i for i in a if i < 0]
cntp = len(pos)
cntn = len(neg)
lst = []

if pos and neg:
    for i in range(1,cntp):
        lst.append((neg[0],pos[i]))
        neg[0] -= pos[i]
    for i in range(1,cntn):
        lst.append((pos[0],neg[i]))
        pos[0] -= neg[i]
    lst.append((pos[0],neg[0]))
    maxv = pos[0]-neg[0]
elif pos:
    pos.sort()
    for i in range(1,cntp-1):
        lst.append((pos[0],pos[i]))
        pos[0] -= pos[i]
    lst.append((pos[cntp-1],pos[0]))
    maxv = pos[cntp-1]-pos[0]
else:
    neg.sort(reverse=True)
    for i in range(1,cntn):
        lst.append((neg[0],neg[i]))
        neg[0] -= neg[i]
    maxv = neg[0]
print(maxv)
for x,y in lst: print(x,y)

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
A.sort()
P=0
Q=[]
if A[0]<=0 and A[-1]>=0:
  B,C=[],[]
  for i in range(N):
    if A[i]==0:
      if len(B)==0:
        B.append(0)
      else:
        C.append(0)
    else:
      if A[i]<0:
        B.append(A[i])
      else:
        C.append(A[i])
  for i in range(len(C)-1):
    Q.append([B[0],C[-1]])
    B[0]-=C[-1]
    del C[-1]
  for i in range(len(B)):
    Q.append([C[0],B[-1]])
    C[0]-=B[-1]
    del B[-1]
  P=C[0]
else:
  if A[0]>0:
    for i in range(N-2,0,-1):
      Q.append([A[0],A[i]])
      A[0]-=A[i]
    Q.append([A[-1],A[0]])
    P=A[-1]-A[0]
  else:
    for i in range(N-1):
      Q.append([A[-1],A[i]])
      A[-1]-=A[i]
    P=A[-1]
print(P)
for i in range(N-1):
  print(*Q[i])

Solution (Python):
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():
    big = A[-1]
    small = A[0]
    res = []
    for i in range(1, N - 1):
        if A[i] > 0:
            res.append((small, A[i]))
            small -= A[i]
        else:
            res.append((big, A[i]))
            big -= A[i]
    res.append((big, small))
    print(big - small)
    for x, y in res:
        print(x, y)


solve()

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


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


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N = I()
A = IL()
ans = []
if min(A)>0:
  A.sort(reverse=True)
  now = A.pop()
  while len(A)>1:
    temp = A.pop()
    ans.append([now,temp])
    now -= temp
  temp = A.pop()
  ans.append([temp,now])
  ANS = temp-now
elif max(A)<=0:
  A.sort()
  now = A.pop()
  while A:
    temp = A.pop()
    ans.append([now,temp])
    now -= temp
  ANS = now
else:
  A.sort(reverse=True)
  MAX = A[0]
  MIN = A[-1]
  for i in range(1,N):
    if A[i]<=0:
      F = i
      break
    ans.append([MIN,A[i]])
    MIN -= A[i]
  now = MAX
  for i in range(F,N-1):
    ans.append([now,A[i]])
    now -= A[i]
  ans.append([now,MIN])
  ANS = now-MIN
print(ANS)
for a,b in ans:
  print(a,b)

Solution (Python):
import math

import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    a = [int(i) for i in ipt().split()]
    a.sort()

    if n == 2:
        print(a[1]-a[0])
        print(a[1],a[0])
    else:
        if a[1] > 0:
            ans = a[0]-a[-1]
            op = [(a[0],a[-1])]
        else:
            ans = a[-1]-a[0]
            op = [(a[-1],a[0])]
        f = True
        for i in range(1,n-2):
            if f and a[i+1] > 0:
                f = False
            if f:
                op.append((max(ans,a[i]),min(ans,a[i])))
                ans = max(ans,a[i])-min(ans,a[i])
            else:
                op.append((min(ans,a[i]),max(ans,a[i])))
                ans = min(ans,a[i])-max(ans,a[i])
        op.append((max(ans,a[n-2]),min(ans,a[n-2])))
        ans = max(ans,a[n-2])-min(ans,a[n-2])
        print(ans)
        for x,y in op:
            print(x,y)


if __name__ == '__main__':
    main()

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
a.sort()
import bisect 
if a[0]*a[-1]<0:
  print(abs(sum([abs(x) for x in a])))
  tmp=a[0]
  t=bisect.bisect_right(a,0)
  for i in range(t+1,n):
    print(tmp,a[i])
    tmp-=a[i]
  a[0]=tmp
  tmp=a[t]
  for i in range(t-1):
    print(tmp,a[i])
    tmp-=a[i]
  print(tmp,a[t-1])

elif a[0]==0:
  print(abs(sum([abs(x) for x in a])))
  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(abs(sum([abs(x) for x in a])))
  tmp=a[-1]
  for i in range(n-2,-1,-1):
    print(tmp,a[i])
    tmp-=a[i]

elif a[0]>0:
  print(sum(a)-2*a[0])
  tmp=a[0]
  for i in range(1,n-1):
    print(tmp,a[i])
    tmp-=a[i]
  print(a[-1],tmp)
else:
  print(abs(sum(a))+2*a[-1])
  tmp=a[-1]
  for i in range(n-2,-1,-1):
    print(tmp,a[i])
    tmp-=a[i]

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

a.sort()
mc = sum(item<0 for item in a)
ans = []
if mc==1 or mc==0:
    val = a[0]
    for i in range(n-2):
        ans.append((val, a[i+1]))
        val = val - a[i+1]
    ans.append((a[n-1], val))
    value = a[n-1] - val
elif mc<n:
    val = a[-1]
    for i in range(mc-1):
        ans.append((val, a[i]))
        val -= a[i]
    val2 = a[mc-1]
    for i in range(mc, n-1):
        ans.append((val2, a[i]))
        val2 -= a[i]
    ans.append((val, val2))
    value = val-val2
else:
    val = a[-1]
    for i in range(n-1):
        ans.append((val, a[i]))
        val -= a[i]
    value = val
        
print(value)
write("\n".join(" ".join(map(str, item)) for item in ans))

Solution (Python):


import sys


def main():
    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 solve(L):
        M = 0
        command = []
        if L[-1] >= 0:
            
            if len(L) > 2:
                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
            else:
                command.append([L[0], L[1]])
                M = L[0] - L[1]
        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()

Solution (Python):
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    A=LI()
    A.sort(reverse=True)
    
    pl=A[0]
    mi=A[-1]
    
    ans=[]
    
    for i in range(N-2):
        a=A[i+1]
        if a>=0:
            ans.append([mi,a])
            mi-=a
        else:
            ans.append([pl,a])
            pl-=a
            
    ans.append([pl,mi])
    print(pl-mi)
    for i in range(len(ans)):
        print(' '.join(map(str, ans[i])))
    

main()

Solution (Python):
n = int(input())
mi = []
pl = []

l = list(map(int,input().split()))
for i in l:
    if i >= 0:
        pl.append(i)
    else:
        mi.append(i)
pl.sort()
mi.sort()
if n == 2:
    print(max(l)-min(l))
    print(max(l),min(l))
    exit()

if pl and mi:
    ans = []
    np = pl[-1]
    for i in range(1,len(mi)):
        ans.append([np,mi[i]])
        np -= mi[i]
    nm = mi[0]
    for i in range(len(pl)-1):
        ans.append([nm,pl[i]])
        nm -= pl[i]
    ans.append([np,nm])
    print(np-nm)
    for i in ans:
        print(*i)
elif pl:
    ans = []
    ans.append([pl[0],pl[1]])
    nm = pl[0]-pl[1]
    for i in range(2,len(pl)-1):
        ans.append([nm,pl[i]])
        nm -= pl[i]
    ans.append([pl[-1],nm])
    print(pl[-1]-nm)
    for i in ans:
        print(*i)
else:
    ans = []
    ans.append([mi[-1],mi[-2]])
    np = mi[-1]-mi[-2]
    for i in range(1,len(mi)-2):
        ans.append([np,mi[i]])
        np -= mi[i]
    ans.append([np,mi[0]])
    print(np-mi[0])
    for i in ans:
        print(*i)

Solution (Python):
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-1):
        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:
        cur = dd[0]
        for i in range(d-1):
            ans.append((cur,dd[i+1]))
            cur -= dd[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)

Solution (Python):
n = int(input())
A = map(int, input().split())

pos = []
neg = []
for a in A:
    if 0 <= a:
        pos.append(a)
    else:
        neg.append(a)


ans = []
if pos:
    if not neg:
        pos.sort(reverse=True)
        neg.append(pos.pop())

    while len(pos) != 1:
        x = pos.pop()
        ans.append((neg[-1], x))
        neg[-1] -= x
else:
    neg.sort()
    pos.append(neg.pop())

pos = pos[0]
while neg:
    x = neg.pop()
    ans.append((pos, x))
    pos -= x

print(pos)
for row in ans:
    print(*row)

Solution (Python):
from collections import deque
n=int(input())
A=sorted(list(map(int,input().split())))
A=deque(A)

N=[]
left,right=A.popleft(),A.pop()
for i in A:
    if i<0:
        N.append([right,i])
        right -=i
    else:
        N.append([left,i])
        left -=i
N.append([right,left])
print(right-left)
for i in N:print(*i)