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:
n = int(input())
A = list(map(int, input().split()))
A.sort()
u, d = A[-1], A[0]
print(sum(abs(a) for a in A) - 2*min(abs(u), abs(d))*int(u*d>0))
for a in A[1:-1]:
    if a<0:
        print(u, a)
        u -= a
    else:
        print(d, a)
        d -= a
print(u, d)

Submission status: Accepted

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

plus, minus = a[0], a[-1]
ans = []
for ai in a[1:-1]:
    if ai < 0:
        ans.append((minus, ai))
        minus -= ai
    elif ai >= 0:
        ans.append((plus, ai))
        plus -= ai
else:
    ans.append((minus, plus))

print(minus - plus)
for x, y in ans:
    print(x, y)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
p = 0
ans = -A[0]
for i in range(1,N-1):
    if A[i] < 0:
        p += 1
        ans -= A[i]
    else:
        ans += A[i]
ans += A[-1]
print(ans)
for i in range(p+1,N-1):
    print(A[p],A[i])
    A[p] -= A[i]
for i in range(p+1):
    print(A[-1],A[i])
    A[-1] -= A[i]

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = list(map(int,input().split()))
A.sort()
if len(A) == 2:
    print(A[1]-A[0])
    print(A[1],A[0])
    exit()
posi = deque([])
nega = deque([])
for i in A:
    if i < 0:
        nega.append(i)
    else:
        posi.append(i)
ans = []
if len(posi) == 0:
    x = nega.pop()
    y = nega.pop()
    posi.append(x-y)
    ans.append([x,y])
if len(nega) == 0:
    x = posi.popleft()
    y = posi.popleft()
    nega.append(x-y)
    ans.append([x,y])

while len(posi) > 1:
    x = nega.pop()
    y = posi.pop()
    ans.append([x,y])
    nega.append(x-y)
while len(nega) > 0:
    x = posi.pop()
    y = nega.pop()
    ans.append([x,y])
    posi.append(x-y)

print(posi[0])
for i in range(N-1):
    print(' '.join(map(str,ans[i])))

Submission status: Accepted

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

A.sort()
S = sum(A)

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

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

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import deque
import bisect

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

A.sort()
A
P, Q = 0, 0
for i in range(N):
    if A[i] >= 0:
        P += 1
    else:
        Q += 1

if P == 0:
    P, Q = 1, N-1
if Q == 0:
    P, Q = N-1, 1

A_p = deque(A[Q:])
A_q = deque(A[:Q])
ans = []
while len(A_p) > 1:
    x = A_q.popleft()
    y = A_p.popleft()
    ans.append([x, y])
    z = x - y
    A_q.appendleft(z)

while A_q:
    x = A_p.pop()
    y = A_q.popleft()
    ans.append([x, y])
    A_p.append(x - y)

M = A_p.pop()
print(M)
for i in range(N-1):
    print(*ans[i])

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import deque

    n = int(readline())
    a = list(map(int, readline().split()))
    a.sort()
    cur = max(a)
    a = a[:n - 1]

    neg = []
    pos = []

    for x in a:
        if x <= 0:
            neg.append(x)
        else:
            pos.append(x)

    seq = []

    if pos:
        pos_que = deque()
        pos_que.extend(pos)
        if neg:
            cur2 = neg.pop()
        else:
            cur2 = pos_que.popleft()
        while pos_que:
            y = pos_que.popleft()
            seq.append([cur2, y])
            cur2 = cur2 - y
        seq.append([cur, cur2])
        cur -= cur2

    for y in neg:
        seq.append([cur, y])
        cur = cur - y

    print(cur)
    for i in range(n - 1):
        print(*seq[i])


if __name__ == '__main__':
    main()

Submission status: Accepted

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

a.sort()

def answer():
    p = sum(1 for i in a if i < 0)
    q = sum(1 for i in a if i >= 0)

    if p == 0:
        p += 1
        q -= 1
    if q == 0:
        p -= 1
        q += 1

    list_xy = []
    for i in range(q - 1):
        list_xy.append((a[0], a[p + i]))
        a[0] -= a[p + i]
    for i in range(p):
        list_xy.append((a[-1], a[i]))
        a[-1] -= a[i]
    return a[-1], list_xy


m, list_xy = answer()

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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#, log2
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
#from decimal import *

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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

#############
# Main Code #
#############

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]

Submission status: Accepted

Solution code:
import sys
from collections import deque

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

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


def main():

    N = in_n()
    A = in_nl()

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

    pa = deque(sorted(pa))
    ma = deque(sorted(ma)[::-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()

Submission status: Accepted

Solution code:

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)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
# 最後の計算で(max)-(min)が必要
# max: 最大値 - ∑負の数
# min: 最小値 - ∑正の数

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)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split(' ')))
    # 何個符号反転できるか？
    # -> 1 ～ N - 1 個反転できる
    # N - 1個: (((v - w) - x) - y) - z
    # N - 2個: ((v - w) - x) - (y - z)
    # ...
    #     2個: (v - w) - ((x - y) - z)
    #     1個: v - (((w - x) - y) - z)
    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:
        # k個が負（1 <= k <= N - 1）：負の値を全て符号反転
        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]  # the last negative element
        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()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

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

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


def solve():
    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()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

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

#############
# Functions #
#############

######INPUT######
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)]

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

#####Shorten#####
def DD(arg): return defaultdict(arg)

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

######Combination######
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

######Factorization######
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

#####MakeDivisors######
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

#####MakePrimes######
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

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

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

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

#####ChangeBase#####
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]

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

#############
# Main Code #
#############

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)

Submission status: Accepted

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

def main():
    n = int(ipt())
    a = [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()

Submission status: Accepted

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