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):
n = int(input())
a = [int(item) for item in input().split()]

suma = 0 
for item in a:
    suma += abs(item)

min_id = -1; min_val = 10**5
max_id = -1; max_val = -10**5
plus_id = -1
minus_id = -1
zero_id = -1

for i, item in enumerate(a):
    if min_val > item:
        min_val = item
        min_id = i
    if max_val < item:
        max_val = item
        max_id = i
    if item == 0:
        zero_id = i
    elif item > 0:
        plus_id = i
    elif item < 0:
        minus_id = i

if minus_id == -1:
    print(suma - 2 * min_val)
    val = min_val
    not_initialized = True
    for i, item in enumerate(a):
        if item == min_val and not_initialized:
            not_initialized = False
            continue
        if i == len(a) - 1 - not_initialized:
            print(item, val)
            continue
        print(val, item)
        val -= item

elif plus_id == -1:
    print(suma - 2 * abs(max_val))
    val = max_val
    not_initialized = True
    for i, item in enumerate(a):
        if item == max_val and not_initialized:
            not_initialized = False
            continue
        print(val, item)
        val -= item

elif plus_id != -1 and minus_id != -1:
    print(suma)
    not_initialized_min = True
    not_initialized_max = True
    minv = min_val
    maxv = max_val
    for i, item in enumerate(a):
        if item == min_val and not_initialized_min:
            not_initialized_min = False
            continue
        if item == max_val and not_initialized_max:
            not_initialized_max = False
            continue
        if item <= 0:
            print(maxv, item)
            maxv -= item
        elif item > 0:
            print(minv, item)
            minv -= item
    print(maxv, minv)
else:
    print(0)
    for i in range(n-1):
        print(0, 0)

Solution (Python):



def ri():
    return int(input())

def rl():
    return list(input().split())

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

def main():
    n = ri()
    la = rli()
    la.sort()
    if la[-1] < 0:
        la.sort(reverse=True)
    lo = []
    

    if la[0] * la[-1] <= 0:
        m = sum(abs(a) for a in la)
        l = la[0]
        r = la[-1]
        la = la[1:-1]
    else:
        m = sum(abs(a) for a in la[2:]) + abs(la[0]-la[1])
        if la[0] < 0:
            l = la[1]
            r = la[0]
        else:
            l = la[0]
            r = la[1]
        la = la[2:]
    while len(la) > 0:
        c = la.pop()
        if c >= 0:
            lo.append((l, r))
            l, r = min(l-r, c), max(l-r, c)
        else:
            lo.append((r, l))
            l, r = min(r-l, c), max(r-l, c)
    if r-l > l-r:
        lo.append((r, l))
    else:
        lo.append((l, r))

    print(m)
    for o in lo:
        print(o[0], o[1])


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    n = int(input())
    arr = list(map(int,input().split()))
    zero = 0
    pos = []
    neg = []
    for i in arr:
        if i > 0:
            pos.append(i)
        elif i < 0:
            neg.append(abs(i))
        else:
            zero += 1

    total = 0
    ans = []
    if pos and neg:
        total = sum(pos)+sum(neg)
        curr = -neg[0]
        for i in range(len(pos)-1):
            ans.append((curr,pos[i]))
            curr = curr-pos[i]

        ans.append((pos[-1],curr))         
        curr = pos[-1]-curr

        for i in range(1,len(neg)):
            ans.append((curr,-neg[i]))
            curr = curr+neg[i]

        for i in range(zero):
            ans.append((curr,0))
    else:
        arr.sort()
        if neg:
            arr.reverse()
        curr = arr[0]
        for i in range(1,n-1):
            ans.append((curr,arr[i]))
            curr = curr-arr[i]

        if pos:
            ans.append((arr[-1],curr))
            total = arr[-1]-curr
        else:
            ans.append((curr,arr[-1]))
            total = curr-arr[-1]

    print(total)
    for i in ans:
        print(i[0],i[1])
        


main()

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

arr.sort()

minus = [x for x in arr if x < 0]
plus = [x for x in arr if x >= 0]

if not minus:
    plus = arr[1:]
    minus = [arr[0]]
elif not plus:
    plus = [arr[-1]]
    minus = arr[:-1]

print(sum(plus) - sum(minus))

plus_max = plus[-1]
plus_rest = plus[:-1]
minus_min = minus[0]
minus_rest = minus[1:]

x = minus_min
while plus_rest:
    y = plus_rest.pop()
    print(x, y)
    x = x - y
minus_min = x

x = plus_max
while minus_rest:
    y = minus_rest.pop()
    print(x, y)
    x = x - y

print(x, minus_min)

Solution (Python):

N =int(input())
A =[int(i)for i in input().split()]
A =sorted(A,key=lambda x:abs(x))
M =A.pop(0)
ans = []
while len(A)!=0:
    num =len(A)
    for n in range(num):
        n = num -1 - n
        if A[n]*M <= 0:
            foo =A.pop(n)
            ans.append([M,foo])
            M = M - foo
    if len(ans)==0:
        foo =A.pop(0)
        ans.append([M,foo])
        M = M -foo
    else:
        a,b = ans[-1]
        ans[-1] = [b,a]
        M = -M

if M < 0:
    a,b = ans[-1]
    ans[-1] = [b,a]
    M = -M

print(M)
prans = "\n".join(["{} {}".format(i,j) for i,j in ans])
print(prans)

Solution (Python):
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit

import heapq as hq
import itertools as its
import operator as op



inf = float('inf')
N = 0


def set_inputs():
    global N
    return


def main():
    setrecursionlimit(100000)
    set_inputs()
    
    n = get_int()
    A = get_li()
    A.sort()
    if n == 2:
        print(A[1] - A[0])
        print(A[1], A[0])
        return
    numbers = deque(A)
    _min = numbers.popleft()
    _max = numbers.pop()
    ans = sum(abs(x) for x in A)
    operations = []
    if _min > 0:
        operations.append((_min, _max))
        ans -= _min * 2
        _min, _max = _min - _max, numbers.pop()
    elif _max < 0:
        operations.append((_max, _min))
        ans += _max * 2
        _min, _max = numbers.popleft(), _max - _min
    
    for x in numbers:
        if x > 0:
            operations.append((_min, x))
            _min -= x
        else:
            operations.append((_max, x))
            _max -= x
    operations.append((_max, _min))
    print(ans)
    for x, y in operations:
        print(x, y)
    return


def get_int():
    return int(input())


def get_float():
    return float(input())


def get_str():
    return input().strip()


def get_li():
    return [int(i) for i in input().split()]


def get_lf():
    return [float(f) for f in input().split()]


def get_lc():
    return list(input().strip())


def get_data(n, types, sep=None):
    if len(types) == 1:
        return [types[0](input().strip()) for _ in range(n)]
    return list(zip(*(
        [t(x) for t, x in zip(types, input().strip().split(sep=sep))]
        for _ in range(n)
    )))


if __name__ == '__main__':
    main()

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

A_max = max(A)
A.remove(A_max)
A_min = min(A)
A.remove(A_min)

moves = []
for i in range(N-2):
    if A[i] <= 0:
        moves.append(str(A_max)+' '+str(A[i]))
        A_max = A_max - A[i]
    else:
        moves.append(str(A_min)+' '+str(A[i]))
        A_min = A_min - A[i]
moves.append(str(A_max)+' '+str(A_min))
print(A_max-A_min)
for move in moves:
    print(move)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
A.sort()
if A[1] >= 0:
	print(sum(A) - 2 * A[0])
	y = A[0]
	for i in range(N - 2):
		print(y, A[i + 1])
		y -= A[i + 1]
	print(A[-1], y)
elif A[-1] < 0:
	print(-sum(A) + 2 * A[-1])
	y = A[-1]
	for i in range(N - 1):
		print(y, A[i])
		y -= A[i]
else:
	n = len([i for i in A if i < 0])
	print(-sum(A[:n]) + sum(A[n:]))
	y = A[0]
	for i in range(N - n - 1):
		print(y, A[-i - 2])
		y -= A[-i - 2]
	print(A[-1], y)
	y = A[-1] - y
	for i in range(n - 1):
		print(y, A[i + 1])
		y -= A[i + 1]

Solution (Python):
import sys
N=int(input())


a=list(map(int,input().split()))
if N==2:
    print(abs(a[0]-a[1]))
    print(max(a),min(a))
    sys.exit()

a.sort()
if a[0]>=0:
    print(sum(a)-2*a[0])
    z=a[0]
    for i in range(1,N-1):
        print(z,a[i])
        z-=a[i]

    print(a[N-1],z)
elif a[N-1]<0:
    ans=[]
    for i in range(N-1):
        ans.append([a[N-1],a[i]])
        a[N-1]-=a[i]
    print(a[N-1])
    for i in range(N-1):
        print(ans[i][0],ans[i][1])

else: 
    ans=[]
    for i in range(1,N-1):
        if a[i]<0:
            ans.append([a[N-1],a[i]])
            a[N-1]-=a[i]
        else:
            ans.append([a[0],a[i]])
            a[0]-=a[i]
    
    ans.append([a[N-1],a[0]])
    print(a[N-1]-a[0])
    for i in range(N-1):
        print(ans[i][0],ans[i][1])

Solution (Python):
n = int(input())
l = sorted(map(int, input().split()))
m = l.pop()
n -= 1
i, res, curr = 1, [], 0
while i < n and l[i] <= 0: i += 1
a, b = l[:i], l[i:]
while b:
    res.append(str(a[0]) + ' ' + str(b[-1]))
    a[0] -= b.pop()
while a:
    res.append(str(m) + ' ' + str(a[-1]))
    m -= a.pop()
print(m)
print('\n'.join(res))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
A = LIST()

flag_plus = False
flag_minus = False
plus_list = []
minus_list = []
zero_list = []
for i in A:
	if i < 0:
		flag_minus = True
		minus_list.append(i)
	elif i > 0:
		flag_plus = True
		plus_list.append(i)
	else:
		zero_list.append(0)



if flag_plus and flag_minus:  
	print(sum([abs(x) for x in A]))
	tmp1 = minus_list.pop(0)
	tmp2 = plus_list.pop(0)
	if plus_list:
		print(tmp1, plus_list[0])
		tmp1 = tmp1 - plus_list[0]  
		for i in range(1, len(plus_list)):  
			print(tmp1, plus_list[i])
			tmp1 = tmp1 - plus_list[i]

	if minus_list:
		print(tmp2, minus_list[0])
		tmp2 = tmp2 - minus_list[0]  
		for i in range(1, len(minus_list)):
			print(tmp2, minus_list[i])
			tmp2 = tmp2 - minus_list[i]
	for i in range(len(zero_list)):
		print(tmp2, 0)
	print(tmp2, tmp1)


elif flag_plus and (not flag_minus):  
	A_min = min(A)
	print(sum(A)-2*A_min)
	A.remove(A_min)
	print(A_min, A[0])
	tmp = A_min - A[0]
	for i in range(1, N-1):
		if i != N-2:
			print(tmp, A[i])
			tmp = tmp - A[i]
		else:
			print(A[i], tmp)
elif (not flag_plus) and flag_minus:  
	A_max = max(A)
	print(sum([abs(x) for x in A])+2*A_max)
	A.remove(A_max)
	print(A_max, A[0])
	tmp = A_max - A[0]
	for i in range(1, N-1):
		print(tmp, A[i])
		tmp = tmp-A[i]
else:  
	print(0)
	for i in range(N-1):
		print(0, 0)

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

if nums[0] >= 0:
	
	print(sum(list(map(abs, nums))) - 2 * nums[0])

	hikareru = nums[0]
	for idx in range(2,n):
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]

	print("{} {}".format(nums[1], hikareru) )

elif nums[-1] <= 0:
	
	print(sum(list(map(abs, nums))) - 2 * (-1)*nums[-1] )

	hikareru = nums[-1]
	for idx in range(n-1):
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]

else:
	print(sum(list(map(abs, nums))) )

	hikareru = nums[0]
	idx = n-2
	while True:
		if nums[idx] < 0:
			break
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]
		idx -= 1

	hiku = hikareru
	print("{} {}".format(nums[n-1], hiku) )
	hikareru = nums[n-1] -  hiku

	idx = 1
	while True:
		if nums[idx] >= 0:
			break
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]
		idx += 1

Solution (Python):
from collections import deque


N = int(input())
A = list(map(int, input().split()))
A.sort()
queue_plus = deque()
queue_minus = deque()
for A_i in A:
    if A_i < 0:
        queue_minus.append(A_i)
    else:
        queue_plus.append(A_i)

xy = [[] for _ in range(N-1)]
cnt = 0
if len(queue_plus) == 0:
    x = queue_minus.pop()
    y = queue_minus.pop()
    xy[cnt] = [x, y]
    cnt += 1
    queue_plus.append(x - y)
elif len(queue_minus) == 0:
    x = queue_plus.popleft()
    y = queue_plus.popleft()
    xy[cnt] = [x, y]
    cnt += 1
    queue_minus.append(x - y)
while len(queue_plus) > 0 and len(queue_minus) > 1:
    x = queue_plus.pop()
    y = queue_minus.pop()
    xy[cnt] = [x, y]
    cnt += 1
    queue_plus.append(x - y)
while len(queue_plus) > 1 and len(queue_minus) > 0:
    x = queue_minus.pop()
    y = queue_plus.pop()
    xy[cnt] = [x, y]
    cnt += 1
    queue_minus.append(x - y)
if len(queue_plus) + len(queue_minus) == 1:
    if len(queue_plus) > 0:
        print(queue_plus.pop())
    else:
        print(queue_minus.pop())
else:
    x = queue_plus.pop()
    y = queue_minus.pop()
    xy[cnt] = [x, y]
    ans = x - y
    print(ans)
for x_y in xy:
    print(" ".join(map(str, x_y)))

Solution (Python):
from collections import deque


def m():
    M = int(input())
    A = deque(sorted([int(i) for i in input().split()]))
    steps = []
    
    maxA = A.pop()
    minA = A.popleft()
    while len(A) > 0:
        b = A.popleft()
        if b > 0:
            steps.append("{} {}".format(minA, b))
            minA -= b
        else:
            steps.append("{} {}".format(maxA, b))
            maxA -= b
    steps.append("{} {}".format(maxA, minA))
    print(maxA - minA)
    for s in steps:
        print(s)


m()

Solution (Python):
def solve():
    N = int(input())
    A = sorted(list(map(int, input().split())))
    cnt0 = 0
    cnt1 = 0
    cnt2 = 0
    for i in range(N):
        if A[i]<0:
            cnt1+=1
        elif A[i]>0:
            cnt2+=1
        else:
            cnt0+=1
    if 0<cnt2+cnt0<N:
        M = sum(list(map(abs, A)))
        print(M)
        hu = A[0]
        sei = A[cnt1]
        tmp1 = sei
        for i in range(1, cnt1):
            print(tmp1, A[i])
            tmp1-=A[i]
        tmp2 = hu
        for i in range(cnt1+1, N):
            print(tmp2, A[i])
            tmp2-=A[i]
        print(tmp1, tmp2)
    elif cnt0 == N:
        print(0)
        for i in range(N-1):
            print(0, 0)
    elif cnt2==0 :
        if cnt0 >0:
            M = sum(list(map(abs, A)))
            print(M)
            hu = A[0]
            sei = A[cnt1]
            tmp1 = sei
            for i in range(1, cnt1):
                print(tmp1, A[i])
                tmp1-=A[i]
            tmp2 = hu
            for i in range(cnt1+1, N):
                print(tmp2, A[i])
                tmp2-=A[i]
            print(tmp1, tmp2)
        else:
            M = -sum(A)+A[-1]*2
            print(M)
            tmp = A[-1]
            for i in range(N-1):
                print(tmp, A[i])
                tmp = tmp-A[i]
    else:
        M = sum(A)-A[0]*2
        print(M)
        tmp = A[0]
        for i in range(1, N-1):
            print(tmp, A[i])
            tmp = tmp-A[i]
        print(A[N-1], tmp)
solve()

Solution (Python):
N = int(input())
plus = []; minus = []
for i in map(int,input().split()):
    if i >= 0:
        plus.append(i)
    else:
        minus.append(i)

lenP = len(plus); lenM = len(minus)

if minus and plus:
    print(sum(plus)-sum(minus))
    for _ in range(lenP-1):
        p = plus.pop(); m = minus.pop()
        print(m, p)
        minus.append(m-p)
    p = plus[0]
    while minus:
        m = minus.pop()
        print(p, m)
        p -= m
    exit()

elif not minus:
    plus = sorted(plus)
    minP = plus[0]
    print(sum(plus)-2*minP)
    if lenP == 2:
        print(plus[1], minP)
        exit()
    for i in range(1, lenP-1):
        print(minP, plus[i])
        minP -= plus[i]
    print(plus[-1], minP)
    exit()

else:
    minus = sorted(minus, reverse=True)
    maxM = minus[0]
    print(2*maxM-sum(minus))
    if lenM == 2:
        print(maxM, minus[1])
        exit()
    for i in range(1, lenM-1):
        print(maxM, minus[i])
        maxM -= minus[i]
    print(maxM, minus[-1])

Solution (Python):
from collections import deque

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

p = 0
n = 0

for a in A:
    if a >= 0:
        p += 1
    else:
        n += 1

ans_list = []

if p == N:
    
    res = A[0]
    for i in range(1,N-1):
        ans_list.append((res,A[i]))
        res -= A[i]
    ans_list.append((A[N-1], res))
    res = A[N-1] - res
    ans = res
elif n == N:
    
    res = A[-1]
    for i in range(N-1):
        ans_list.append((res, A[i]))
        res -= A[i]
    ans = res
else:
    
    p_list = deque()
    n_list = deque()
    for a in A:
        if a >= 0:
            p_list.append(a)
        else:
            n_list.append(a)
    while len(p_list) != 1:
        np = p_list.pop()
        nn = n_list.pop()
        ans_list.append((nn, np))
        n_list.append(nn-np)
    res = p_list[0]
    for nn in n_list:
        ans_list.append((res, nn))
        res -= nn
    ans = res

print(ans)
for x,y in ans_list:
    print(x,y)

Solution (Python):
import heapq
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")

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



















enable = [True] * N
mins = [(a, i) for i, a in enumerate(A)]
maxes = [(-a, i) for i, a in enumerate(A)]
heapq.heapify(mins)
heapq.heapify(maxes)

ans = []
for _ in range(N - 2):
    x, xi = heapq.heappop(maxes)
    x *= -1
    y, yi = heapq.heappop(mins)
    enable[xi] = False
    enable[yi] = False
    while not enable[maxes[0][1]]:
        heapq.heappop(maxes)
    while not enable[mins[0][1]]:
        heapq.heappop(mins)
    next_max = -maxes[0][0]
    next_min = mins[0][0]
    if abs(x - y - next_min) < abs(y - x - next_max):
        x, y = y, x
    enable.append(True)
    heapq.heappush(mins, (x - y, len(enable) - 1))
    heapq.heappush(maxes, (y - x, len(enable) - 1))
    ans.append((x, y))

x = -maxes[0][0]
y = mins[0][0]
ans.append((x, y))
print(x - y)
for a in ans:
    print(*a)

Solution (Python):
import heapq

N = int(input())
A = [int(x) for x in input().split()]

max_value = max(A)
positive = []
negative = []
flag = True
for a in A:
    if a == max_value and flag:
        flag = False
        continue
    elif a > 0:
        heapq.heappush(positive, a)
    else:
        negative.append(a)

if len(negative) > 0:
    nega = negative.pop()
else:
    nega = heapq.heappop(positive)

actions = []
while len(positive) > 0:
    y = heapq.heappop(positive)
    actions.append((nega, y))
    nega = nega - y

negative.append(nega)

while len(negative) > 0:
    y = heapq.heappop(negative)
    actions.append((max_value, y))
    max_value = max_value - y

print(max_value)
for action in actions:
    x, y = action
    print("{} {}".format(x, y))

Solution (Python):
import sys
import numpy as np

N = sys.stdin.readline()
a = np.fromstring(sys.stdin.readline(), dtype='i4', sep=' ')
a.sort()
p = a[a <= 0]
q = a[a > 0]

if len(p) == 0:
    print(np.sum(q[1:]) - q[0])
    t = q[0]
    for c in q[1:-1]:
        print(str(t) + ' ' + str(c))
        t -= c
    print(str(q[-1]) + ' ' + str(t))
elif len(q) == 0:
    print(p[-1] - np.sum(p[:-1]))
    t = p[-1]
    for c in p[:-1]:
        print(str(t) + ' ' + str(c))
        t -= c
else:
    print(sum(q) - sum(p))
    t = p[0]
    for c in q[:-1]:
        print(str(t) + ' ' + str(c))
        t -= c
    print(str(q[-1]) + ' ' + str(t))
    t = q[-1] - t
    for c in p[1:]:
        print(str(t) + ' ' + str(c))
        t -= c

Solution (Python):
def bs_left(l, target): 
    low, high = 0, len(l)
    while low < high:
        mid = (low+high)//2
        if l[mid] < target:
            low = mid+1
        else:
            high = mid
    if low == len(l):
        return -1
    return low
N = int(input())
A = list(map(int,input().split()))
A.sort()
if A[N-1] <= 0:
    print(2*A[N-1]-sum(A))
    x = A[N-1]
    for i in range(N-1):
        y = A[N-2-i]
        print(x,y)
        x = x-y

else:
    id = bs_left(A,0)
    
    s = -A[0]
    for i in range(1,N):
        if i < id:
            s -= A[i]
        else:
            s += A[i]
    print(s)
    if id == 0:
        x = A[0]
        for i in range(1,N-1):
            y = A[i]
            print(x,y)
            x = x-y
        print(A[N-1],x)
    else:
        x = A[0]
        for i in range(id,N-1):
            y = A[i]
            print(x,y)
            x = x-y

        print(A[N-1],x)
        x = A[N-1]-x
        for i in range(1,id):
            y = A[i]
            print(x,y)
            x = x-y

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

A.sort()
if A[-1] < 0:
    s = A[-1]
    sa_list = []
    for a in A[:-1]:
        sa_list.append((s, a))
        s -= a
    print(s)
    for s, a in sa_list:
        print(s, a)
elif 0 <= A[0]:
    s = A[0]
    sa_list = []
    for a in A[1:-1]:
        sa_list.append((s, a))
        s -= a
    sa_list.append((A[-1], s))
    A[-1] -= s 
    print(A[-1])
    for s, a in sa_list:
        print(s, a)
else:
    s = A[-1]
    sa_list = []
    end = None
    for i, a in enumerate(A):
        if i == 0:
            continue
        if 0 <= a:
            end = i
            break
        sa_list.append((s, a))
        s -= a
    t = A[0]
    for a in A[end:-1]:
        sa_list.append((t, a))
        t -= a
    sa_list.append((s, t))
    s -= t
    print(s)
    for s, a in sa_list:
        print(s, a)

Solution (Python):



n = int(input())
a = [int(i) for i in input().split()]


pmin = 10**9
pind = -1
qmax =  -10**9
qind = -1

for j,i in enumerate(a):
    if 0 <= i < pmin:
        pmin = i
        pind = j
    if qmax < i < 0:
        qmax = i 
        qind = j




pmax = pmin

if pind == -1: 
    ans = -sum(a) + 2*a[qind]
    print(ans)
    for i, ai in enumerate(a):
        if i != qind:
            print(qmax,ai)
            qmax -= ai

    exit()
    
elif qind == -1: 
    ans = sum(a) - 2*a[pind]
    print(ans)
    if pind == 0:
        for i in range(2,n):
            print(pmax, a[i])
            pmax -= a[i]
        print(a[1], pmax)
    else:
        for i in range(1,n):
            if i==pind: continue
            print(pmax, a[i])
            pmax -= a[i]
        print(a[0], pmax)
    exit()

else:

    ans = 0
    for ai in a:
        ans += abs(ai)
    print(ans)
    for i, ai in enumerate(a):
        if i == pind or i == qind: continue
        if ai <= 0:
            print(pmax, ai)
            pmax -= ai
        if ai > 0:
            print(qmax,ai)
            qmax -= ai
    print(pmax,qmax)

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

A.sort()

for x in range(N):
    if A[x]>0:
        break

if x==0:
    x=1

if x==1:
    temp = A[0]
    ans = []
    for i in range(N-2):
        ans.append(str(temp)+" "+str(A[i+1]))
        temp-=A[i+1]
    ans.append(str(A[-1]) +" " + str(temp))
    temp=A[-1]-temp
elif x==N-1:
    temp = A[-1]
    ans = []
    for i in range(N-1):
        ans.append(str(temp)+" "+str(A[N-2-i]))
        temp-=A[N-2-i]
else:
    temp = A[0]
    ans = []
    for i in range(N-x-1):
        ans.append(str(temp)+" "+str(A[N-2-i]))
        temp-=A[N-2-i]
    temp1 = A[-1]
    for i in range(1,x):
        ans.append(str(temp1)+" "+str(A[i]))
        temp1-=A[i]
    ans.append(str(temp1)+" " + str(temp))
    temp = temp1-temp

print(temp)
for a in ans:
    print(a)

Solution (Python):
def getlist():
	return list(map(int, input().split()))

N = int(input())
A = getlist()
A = sorted(A)

if A[0] >= 0:
	M = sum(A) - 2 * A[0]
	print(M)
	x = A[0]
	for i in range(N - 2):
		y = A[i + 1]
		print(x, y)
		x -= y
	print(A[-1], x)

elif A[-1] <= 0:
	M = -sum(A) + 2 * A[-1]
	print(M)
	x = A[-1]
	for i in range(N - 2):
		y = A[-2 - i]
		print(x, y)
		x -= y
	print(x, A[0])

else:
	M = 0
	for i in range(N):
		M += abs(A[i])
	print(M)

	for i in range(N):
		if A[i] > 0:
			n = i
			break

	Ll = []
	Rl = []
	for i in range(N):
		if A[i] < 0:
			Ll.append(A[i])
		else:
			Rl.append(A[i])
	ln = len(Ll)
	rn = len(Rl)
	x = Ll[0]
	for i in range(rn - 1):
		y = Rl[i]
		print(x, y)
		x -= y
	Ll[0] = x
	x = Rl[-1]
	for i in range(ln):
		y = Ll[i]
		print(x, y)
		x -= y

Solution (Python):
N = int(input())
As = list(map(int, input().split()))

As.sort()
minA = min(As)
maxA = max(As)

anss = []
x = maxA
x2 = minA
for A in As[1:-1]:
    if A <= 0:
        anss.append((x, A))
        x -= A
    else:
        anss.append((x2, A))
        x2 -= A

anss.append((x, x2))
x -= x2

print(x)
print('\n'.join(map(lambda x: str(x[0])+' '+str(x[1]), anss)))

Solution (Python):



N = int(input())

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


A = sorted(A)
ans = A[-1] - A[0]
A_nashi = A[1:-1]

plus = len(A_nashi)
for i in range(len(A_nashi)):
    if A_nashi[i] >= 0:
        plus = i
        break

ans += sum(A_nashi[plus:]) - sum(A_nashi[:plus])

print(ans)

res = A[0]
for i in range(len(A_nashi) - plus):
    print(res,A_nashi[-i-1])
    res -= A_nashi[-i-1]
    
print(A[-1], res)
res = A[-1] - res

for i in range(plus):
    print(res,A_nashi[i])
    res -= A_nashi[i]

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

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

A.sort()

if N==2:
    print(str(A[1]-A[0])+'\n'+str(A[1])+' '+str(A[0]))
    

else:
    ans_li=[]
    mainus = [x for x in A if x<0]
    plus = [x for x in A if x>=0]
    
    if len(plus)<2:
        before_result=A[-1]
        for i in range(N-1):
            ans_li.append(str(before_result)+' '+str(A[i]))
            before_result = before_result - A[i]
        print(str(before_result))
        for a in ans_li:
            print(a)
    elif len(mainus)<2:
        before_result=A[0]
        for i in range(N-1)[1:]:
            ans_li.append(str(before_result)+' '+str(A[i]))
            before_result = before_result - A[i]
        ans_li.append(str(A[-1])+' '+str(before_result))
        before_result = A[-1]-before_result
        print(str(before_result))
        for a in ans_li:
            print(a)
    else:
        before_result=mainus[0]
        for i in range(len(plus)-1):
            ans_li.append(str(before_result)+' '+str(plus[i]))
            before_result = before_result - plus[i]
        mainus[0] = before_result
        for i in range(len(mainus)):
            ans_li.append(str(plus[-1])+' '+str(mainus[i]))
            plus[-1] = plus[-1]-mainus[i]
        print(str(plus[-1]))
        for a in ans_li:
            print(a)

Solution (Python):
N=int(input())
A=list(map(int,input().strip().split(' ')))
A=sorted(A)[::-1]
change=len(A)-1
for i in range(len(A)):
    if A[i]<0:
        change=i
        break

if change==0:
    change=1
MAX=sum(A[:change])+sum([-A[i] for i in range(change,len(A))])


prefix=[]
pre=0
for i in range(len(A)):
    if i<change:
        pre+=A[i]
        prefix+=[pre]
    else:
        pre-=A[i]
        prefix+=[pre]

queries=[]

if change>=2:
    pre=A[change]
    for i in range(change-1):
        queries+=[(pre,A[i])]
        pre-=A[i]
    queries+=[(A[change-1],pre)]
    pre=A[change-1]-pre
    for i in range(change+1,len(A)):
        queries+=[(pre,A[i])]
        pre-=A[i]
else:
    pre=A[0]
    for i in range(1,len(A)):
        queries+=[(pre,A[i])]
        pre-=A[i]

print(MAX)
for (a,b) in queries:
    print(a,b)

Solution (Python):


import math

def main():
    n = int(raw_input())
    an = map(int,raw_input().split())
    mi = min(an)
    mx = max(an)
    total = mx - mi
    an.remove(mi)
    an.remove(mx)
    for a in an:
        total += abs(a)
    print total
    if n == 2:
        print mx,mi
    else:
        for a in an:
            if a < 0:
                print mx,a
                mx = mx - a
            else:
                print mi,a
                mi = mi - a
        print mx,mi

if __name__ == "__main__":
    main()

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

plus_len = len(list(filter(lambda x:x>0,A)))
minus_len = len(list(filter(lambda x:x<0,A)))

if plus_len==N: 
    A = sorted(A,reverse=True)
    OUT = []
    for j in range(1,N):
        x = A.pop()
        y = A.pop()
        if j==N-1:
            OUT.append([y,x])
            A.append(y-x)
        else:
            OUT.append([x,y])
            A.append(x-y)
    print(A[0])
    for o in OUT:
        print("{} {}".format(o[0],o[1]))
        
elif minus_len==N:
    A = sorted(A)
    OUT = []
    for j in range(1,N):
        x = A.pop()
        y = A.pop()
        OUT.append([x,y])
        A.append(x-y)
    print(A[0])
    for o in OUT:
        print("{} {}".format(o[0],o[1]))
    
else: 
    A = sorted(A)
    OUT = []
    max_side = A.pop(N-1)
    min_side = A.pop(0)
    for i in range(len(A)):
        if A[i]<0:
            OUT.append([max_side,A[i]])
            max_side -= A[i]
        else:
            OUT.append([min_side,A[i]])
            min_side -= A[i]
    OUT.append([max_side,min_side])
    print(max_side-min_side)
    for o in OUT:
        print("{} {}".format(o[0],o[1]))

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

a.sort()

if a[0]<=0 and a[-1]>=0:
    m = 0
    for i in range(n):
        m+=abs(a[i])
elif a[0]>0:
    m = sum(a)-a[0]*2
else:
    m = a[-1]
    for i in range(n-1):
        m+=abs(a[i])

print(m)

b = [a[0]] 
c = [] 

for i in range(1,n-1):
    if a[i]<0:
        b.append(a[i])
    else:
        c.append(a[i])

for x in c:
    print(b[-1],end=' ')
    print(x)
    b[-1]-=x
for y in b:
    print(a[-1],end=' ')
    print(y)
    a[-1]-=y