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: Accepted

Solution code:
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


# globals
inf = float('inf')
N = 0


def set_inputs():
    global N
    return


def main():
    setrecursionlimit(100000)
    set_inputs()
    # ----------MAIN----------
    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
    # _min <= 0 and 0 <= _max
    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()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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]

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

# print(plus_list)
# print(minus_list)
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]  # tmp1 はマイナスの集約
		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]  # tmp2は プラスの集約
		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:  # 正も負もなし(全部0)
	print(0)
	for i in range(N-1):
		print(0, 0)

Submission status: Accepted

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

if nums[0] >= 0:
	# all 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:
	# all 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

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
from collections import deque


def m():
    M = int(input())
    A = deque(sorted([int(i) for i in input().split()]))
    steps = []
    # get last A
    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()

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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:
    #ans = sum(A[1:]) - A[0]
    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:
    #ans = -sum(A[:-1]) + A[-1]
    res = A[-1]
    for i in range(N-1):
        ans_list.append((res, A[i]))
        res -= A[i]
    ans = res
else:
    #ans = sum([abs(a) for a in A])
    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)

Submission status: Accepted

Solution code:
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()))

# ans = []
# while len(A) > 2:
#     x = max(A)
#     y = min(A)
#     A = A[1:-1]
#     next_max = max(A)
#     next_min = min(A)
#     if abs(x - y - next_min) < abs(y - x - next_max):
#         x, y = y, x
#     bisect.insort_left(A, x - y)
#     ans.append((x, y))
# x, y = max(A), min(A)
# ans.append((x, y))
# print(x - y)
# for a in ans:
#     print(*a)


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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
def bs_left(l, target): # l=sortedのリスト, target以上の値をもつ要素のうち一番左のindexを返す
    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)
    #print(id)
    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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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

#print(a)
#print(pmin,qmax, "pmin", "pmax")

pmax = pmin

if pind == -1: # 非負が0個
    ans = -sum(a) + 2*a[qind]
    print(ans)
    for i, ai in enumerate(a):
        if i != qind:
            print(qmax,ai)
            qmax -= ai
#            print(qind, i)
    exit()
    
elif qind == -1: # 負が0個
    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:
#    print("pq")
    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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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]

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# coding:utf-8

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()

Submission status: Accepted

Solution code:
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: #0を含むか，2つの符号が存在すればsum(abs)でOK
    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]))

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
plus=[a for a in A if a>0]
mainus=[a for a in A if a<=0]
plus.sort()
mainus.sort(reverse=True)
if len(mainus)==0:
    print(sum(plus)-2*plus[0])
    now=plus[0]
    for i in range(1,len(plus)-1):
        print(str(now)+" "+str(plus[i]))
        now-=plus[i]
    print(str(plus[-1])+" "+str(now))
elif len(plus)==0:
    print(-1*sum(mainus)+2*mainus[0])
    now=mainus[0]
    for i in range(1,len(mainus)):
        print(str(now)+" "+str(mainus[i]))
        now-=mainus[i]
else:
    print(sum(plus)-sum(mainus))
    now=mainus[0]
    for i in range(len(plus)-1):
        print(str(now)+" "+str(plus[i]))
        now-=plus[i]
    if len(plus)>0:
        print(str(plus[-1])+" "+str(now))
        now=plus[-1]-now
    for i in range(1,len(mainus)):
        print(str(now)+" "+str(mainus[i]))
        now-=mainus[i]

Submission status: Accepted

Solution code:
import collections

def solve():
  n = int(input())
  a = collections.deque(sorted(list(int(i) for i in input().split())))
  big = a.pop()
  mini = a.popleft()
  queue = collections.deque([])
  #print(big,mini)
  while (a):
    if a[0] <= 0:
      tmp = a.popleft()
      queue.append((big,tmp))
      big -= tmp
    else:
      tmp = a.pop()
      queue.append((mini,tmp))
      mini -= tmp
  print(big-mini)
  queue.append((big,mini))
  for i in range(len(queue)):
    print(*queue[i])
  
solve()

Submission status: Accepted

Solution code:
N = int(input())
A = [int(a) for a in input().split()]
B = [abs(a) for a in A]

for i in range(N):
    if A[i] > 0:
        po = i
        break
else:
    po = -1
for i in range(N):
    if A[i] < 0:
        ne = i
        break
else:
    ne = -1
mi = min(B)
for i in range(N):
    if B[i] == mi:
        mii = i
        break
else:
    mii = -1

if po >= 0 and ne >= 0:
    print(sum(B))
    t1, t2 = A[po], A[ne]
    if po > ne:
        po, ne = ne, po
    # print("pone =", po, ne)
    if po == ne:
        del A[ne]
        A = [0] + A
    else:
        del A[ne]
        del A[po]
        A = [t1, t2] + A
else:
    print(sum(B) - 2 * mi)
    t = A[mii]
    del A[mii]
    A = [t] + A
# print(A)
prev = A[0]
for i in range(1, N):
    a, b = max(prev, A[i]), min(prev, A[i])
    if i == N-1 or A[i+1] < 0:
        print(a, b)
        prev = a - b
    else:
        print(b, a)
        prev = b - a

Submission status: Accepted

Solution code:
import bisect
m = int(input())
a = list(map(int,input().split()))
a.sort()

if a[-1] <= 0: #ok
    a1 = -(sum(a)) + 2 * a[-1]
    print(a1)
    p = a[-1]
    q = a[-2]
    for i in range(-1,-(len(a)),-1):
        print(str(p)+ " " + str(q))
        if i == -(len(a) -1):
            break
        p = p - q
        q = a[i-2]
elif a[0] >= 0:
    print(sum(a[1:]) - a[0])
    p = a[0]
    q = a[1]
    for i in range(len(a)-1):
        print(str(p)+" "+str(q))
        p = p - q
        if i + 2 > len(a) - 2:
            break 
        q = a[i+2]
    print(str(a[-1])+" "+str(p))
else:
    c = bisect.bisect_left(a,0)
    c1 = 0
    for x in a:
        c1 += abs(x)
    print(c1)
    p = a[c-1]
    q = a[c]
    for i in range(c,m-1):
        print(str(p)+" "+str(q))
        p = p - q
        q = a[i+1]
    p1 = a[-1]
    q1 = a[0]
    for i in range(c-1):
        print(str(p1)+" "+str(q1))
        p1 = p1 - q1
        q1 = a[i+1]
    print(str(p1)+ " "+str(p))

Submission status: Accepted

Solution code:
import bisect

N = int(input())
a_list = list(map(int, input().split()))

a_list.sort()

M = 0
commands = []
item_max = a_list.pop()
item_min = a_list.pop(0)

cur_x = item_min
while a_list and a_list[-1] > 0:
	cur_y = a_list.pop()
	commands.append((cur_x, cur_y))
	cur_x -= cur_y

commands.append((item_max, cur_x))
cur_x = item_max - cur_x
while a_list:
	cur_y = a_list.pop()
	commands.append((cur_x, cur_y))
	cur_x -= cur_y

print(cur_x)
for x, y in commands:
	print(x, y)