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:

def solve():
    N = int(input())
    As = [int(i) for i in input().split()]
    As.sort()
    maxA = As.pop()
    minA = As.pop(0)
    upper0A = [i for i in As if i >= 0]
    lower0A = [i for i in As if i < 0]
    # print('maxA:', maxA)
    # print('minA:', minA)
    # print('upper0A:', upper0A)
    # print('lower0A:', lower0A)
    result_load = []
    for uA in upper0A:
        result_load.append([minA, uA])
        minA = minA - uA
    for lA in lower0A:
        result_load.append([maxA, lA])
        maxA = maxA - lA
    result_load.append([maxA, minA])
    resultA = maxA - minA

    # export
    print(resultA)
    for x, y in result_load:
        print(x, y)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush

def solve():
    N = int(input())
    A0, A1 = [], []
    for a in map(int, input().split()):
        if a >= 0:
            heappush(A0,a)
        else:
            heappush(A1,-a)
    if A0 and A1:
        S = sum(A0) + sum(A1)
        res_l = [str(S)]
        b = heappop(A0)
        while len(A1) > 1:
            a = -heappop(A1)
            res_l.append('{} {}'.format(b, a))
            b -= a
        c = b
        b = -heappop(A1)
        while A0:
            a = heappop(A0)
            res_l.append('{} {}'.format(b, a))
            b -= a
        res_l.append('{} {}'.format(c, b))                
    else:
        if A0:
            S = sum(A0)
            b = heappop(A0)
            S -= 2*b
            res_l = [str(S)]
            for _ in range(N-2):
                a = heappop(A0)
                res_l.append('{} {}'.format(b, a))
                b -= a
            a = heappop(A0)
            res_l.append('{} {}'.format(a, b))
        else:
            S = sum(A1)
            b = -heappop(A1)
            S = S+2*b
            res_l = [str(S)]
            for _ in range(N-1):
                a = -heappop(A1)
                res_l.append('{} {}'.format(b, a))
                b -= a
    res =  '\n'.join(res_l)

    return res
if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    pos = []
    neg = []
    for i in range(N):
        if A[i] < 0:
            neg.append(A[i])
        else:
            pos.append(A[i])
    pos.sort()
    neg.sort(reverse=True)
    ans = sum(map(abs, A))
    if len(pos) == N:
        x = pos.pop(0)
        ans -= x * 2
        neg.append(x)
    elif len(neg) == N:
        x = neg.pop(0)
        ans += x * 2
        pos.append(x)
    print(ans)
    n = 1
    p = 1
    x = pos[0]
    y = neg[0]
    while p < len(pos):
        print(y, pos[p])
        y -= pos[p]
        p += 1
    while n < len(neg):
        print(x, neg[n])
        x -= neg[n]
        n += 1
    print(x, y)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
a.sort()
min_ = a[0]
max_ = a[-1]
if min_ == max_:
    if n == 2:
        print(0)
        print(max_, max_)
        exit()
    if min_ < 0:
        print(-min_ * (n - 2))
        print(min_, min_)
        for i in range(n - 2):
            print(i * min_, min_)
    else:
        print(min_ * (n - 2))
        print(max_, max_)
        for i in range(n - 3):
            print(i * min_, min_)
        print(max_, -(n - 3) * max_)
else:
    ans = ''
    if min_ >= 0:
        for i in range(1, n - 1):
            ans += str(min_) + ' ' + str(a[i]) + '\n'
            min_ -= a[i]
        ans += str(a[-1]) + ' ' + str(min_) + '\n'
        print(a[-1] - min_)
        print(ans, end='')
    elif max_ <= 0:
        for i in range(n - 1):
            ans += str(max_) + ' ' + str(a[i]) + '\n'
            max_ -= a[i]
        print(max_)
        print(ans, end='')
    else:
        for i in range(1, n - 1):
            if a[i] < 0:
                continue
            else:
                ans += str(min_) + ' ' + str(a[i]) + '\n'
                min_ -= a[i]
        ans += str(max_) + ' ' + str(min_) + '\n'
        max_ -= min_
        for i in range(1, n - 1):
            if a[i] >= 0:
                break
            else:
                ans += str(max_) + ' ' + str(a[i]) + '\n'
                max_ -= a[i]
        print(max_)
        print(ans, end='')

Submission status: Accepted

Solution code:
inpl = lambda: list(map(int,input().split()))

def output(plus,minus):
    print(sum(plus)-sum(minus))
    p = plus[0]
    for z in minus[1:]:
        print(p,z)
        p -= z
    q = minus[0]
    for w in plus[1:]:
        print(q,w)
        q -= w
    print(p,q)

N = int(input())
A = inpl()
plus = list(filter(lambda x: x>0, A))
minus = list(filter(lambda x: x<0, A))
Np = len(plus)
Nm = len(minus)
Nz = N-Np-Nm

if Np == N:
    plus.sort(reverse=True)
    minus = [plus.pop()]
elif Nm == N:
    minus.sort()
    plus = [minus.pop()]
elif Nz == N:
    plus = [0]*(Nz-1)
    minus = [0]
else:
    if Nm == 0:
        minus = [0]*Nz
    else:
        plus.extend([0]*Nz)

output(plus,minus)

Submission status: Accepted

Solution code:
import numpy as np
N = int(input())
A = sorted(list(map(int, input().split())))
B = np.array(A)
tmp = set(B)

if len(tmp) > 1:
    t = sum(np.abs(B))
    if A[0] > 0:
        print(t-A[0]*2)
    elif A[-1] < 0:
        print(t+A[-1]*2)
    else:
        print(t)
else:
    print((N - 2) * abs(A[0]))

for i in range(N-2):
    x = A.pop(0)
    y = A.pop(-1)
    if x > y:
        tmp = x
        x = y
        y = tmp
    if A[0] > 0:
        print(x, y)
        A.append(x-y)
    else:
        print(y, x)
        A.append(y-x)
x = A[0]
y = A[1]
if x > y:
    print(x, y)
else:
    print(y, x)

Submission status: Accepted

Solution code:
N = int(input())

#As = [int(elm) for elm in input().split(" ")]
As = []
minus_As = []
plus_As = []
minus_count = 0
plus_count = 0
for elm in input().split(" "):
    A = int(elm)
    if A >= 0:
        plus_As.append(A)
        plus_count += 1
    else:
        minus_As.append(A)
        minus_count += 1
    As.append(A)

cond1 = plus_count > 0
cond2 = minus_count > 0
# 両方
case1 = cond1 and cond2
# 全て非負の場合
case2 = cond1 and (not cond2)
# 全てマイナスの場合
case3 = (not cond1) and cond2

out_txts = []
if case1:
    max_val = max(plus_As)
    max_i = plus_As.index(max_val)

    mA = minus_As[0]
    for i, pA in enumerate(plus_As):
        if i == max_i:
            continue
        out_txts.append("%d %d" % (mA, pA))
        mA -= pA
    minus_As[0] = mA

    out = max_val
    for mA in minus_As:
        out_txt = "%d %d" % (out, mA)
        out_txts.append(out_txt)
        out -= mA
elif case2:
    max_val = max(plus_As)
    max_i = plus_As.index(max_val)
    del plus_As[max_i]

    min_val = min(plus_As)
    min_i = plus_As.index(min_val)
    del plus_As[min_i]

    minA = min_val
    for i, pA in enumerate(plus_As):
        #if i in [min_i, max_i]:
        #    continue
        out_txt = "%d %d" % (minA, pA)
        out_txts.append(out_txt)
        minA -= pA
    
    out_txt = "%d %d" % (max_val, minA)
    out_txts.append(out_txt)
    out = max_val - minA

else:
    max_val = max(minus_As)
    max_i = minus_As.index(max_val)
    del minus_As[max_i]

    out = max_val
    for i, mA in enumerate(minus_As):
        #if max_i == i:
        #    continue
        out_txt = "%d %d" % (out, mA)
        out_txts.append(out_txt)
        out -= mA

#print("case", case1, case2, case3)
print(out)
for out_txt in out_txts:
    print(out_txt)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort()
anslist = []
for i in range(1, n - 1):
    if a[i] >= 0:
        anslist.append([a[0], a[i]])
        a[0] -= a[i]
    else:
        anslist.append([a[-1], a[i]])
        a[-1] -= a[i]

anslist.append([a[-1], a[0]])
ans = a[-1] - a[0]
print(ans)
for i, j in anslist:
    print(i, j)
#
# a.sort()
# ans = a[0]
# for i in range(1, n - 1):
#     ans += a[i] * (-1)
#
# print(a[-1] - ans)
# key = a[0]
# for i in range(1, n - 1):
#     print(key, a[i])
#     key = key - a[i]
# print(a[-1], key)

# a.sort()
# plusa = []
# minusa = []
# for i in a[1:-1]:
#     if i < 0:
#         minusa.append(i)
#     else:
#         plusa.append(i)
# #
# # print(minusa, plusa)
# anslist = []
# # if len(a) == 2:
# #     print(max(a) - min(a))
# #     print(max(a), min(a))
# # if min(a) >= 0:
# #     for i in range(1, n - 1):
# #         anslist.append([a[0], a[i]])
# #         a[0] -= a[i]
# #     anslist.append([a[-1], a[0]])
# #     print(a[-1] - a[0])
# #     for i, j in anslist:
# #         print(i, j)
# # else:
# #     if len(plusa) == 0:
# #         plusa.append(minusa[-1])
# #         del minusa[-1]
# #
# #     for i in minusa:
# #         # print(plusa[0], i)
# #         anslist.append([plusa[0], i])
# #         plusa[0] -= i
# #
# #     for i in plusa:
# #         # print(a[0], i)
# #         anslist.append([a[0], i])
# #         a[0] -= i
# #     # print(a[0])
# #     print(a[-1] - a[0])
# #     for i, j in anslist:
# #         print(i, j)
# #     # print(anslist)
# #     print(a[-1], a[0])

Submission status: Accepted

Solution code:
#!venv/bin/python
 
import math
import numpy as np
import random
import copy
import statistics 
import bisect
import heapq
from collections import defaultdict 
import time
import sys
from pprint import pprint

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

min_heap = []
max_heap = []

for a in A:
    heapq.heappush(min_heap, a)
    heapq.heappush(max_heap, -a)

ans = []
for i in range(N-2):
    max = -heapq.heappop(max_heap)
    min = heapq.heappop(min_heap)
    diff = max - min
    new_val = 0
    if -max_heap[0] - (-diff) > diff - min_heap[0]:
        ans.append("{} {}".format(min,max))
        new_val = -diff
    else:
        ans.append("{} {}".format(max,min))
        new_val = diff
    heapq.heappush(max_heap, -new_val)
    heapq.heappush(min_heap, new_val)

print( -max_heap[0] - min_heap[0]  )
for a in ans:
    print(a)
print("{} {}".format(-max_heap[0], min_heap[0]))

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = list(map(int, input().split()))
A.sort()
q = deque(A)
ansq = deque()
i = 0
while i != N - 2:
    """if i % 2 == 0:
        l, r = q.popleft(), q.pop()
        q.appendleft(l - r)
        ansq.append((l,  r))
    else:
        l, r = q.popleft(), q.pop()
        q.append(r - l)
        ansq.append((r,  l))"""
    l, r = q.popleft(), q.pop()
    if l < 0 and r < 0: # どちらもマイナス
        if l < r:
            q.append(r - l)
            ansq.append((r, l))
        else:
            q.append(l - r)
            ansq.append((l, r))
    elif l >= 0 and r >= 0: # どちらもプラス
        if l < r:
            q.appendleft(l - r)
            ansq.append((l, r))
        else:
            q.appendleft(r - l)
            ansq.append((r, l))
    else: # 異符号
        if abs(r - l - q[-1]) > abs(q[0] - l + r):
            q.append(r - l)
            ansq.append((r, l))
        else:
            q.appendleft(l - r)
            ansq.append((l, r))
    i += 1
print(q[1] - q[0])
for ans in ansq:
    print("{} {}".format(ans[0], ans[1]))
print(q[1], q[0])

Submission status: Accepted

Solution code:
import heapq
n=int(input())
Ans=[]
A=[int(i) for i in input().split()]
A.sort()
if A[0]>=0:
  Ans=[]
  heapq.heapify(A)
  for i in range(n-2):
    a1=heapq.heappop(A)
    a2=heapq.heappop(A)
    Ans.append([a1,a2])
    heapq.heappush(A,a1-a2)
  a1=heapq.heappop(A)
  a2=heapq.heappop(A)
  Ans.append([a2,a1])
  print(a2-a1)
  for i in range(n-1):
    print(*Ans[i])

elif A[-1]<=0:
  Ans=[]
  AA=[]
  for i in range(n):
    AA.append(-A[i])
  heapq.heapify(AA)
  for i in range(n-2):
    a1=heapq.heappop(AA)
    a2=heapq.heappop(AA)
    Ans.append([-a1,-a2])
    heapq.heappush(AA,-(a2-a1))
  a1=heapq.heappop(AA)
  a2=heapq.heappop(AA)
  Ans.append([max(-a2,-a1),min(-a2,-a1)])
  print(max(-a2,-a1)-min(-a2,-a1))
  for i in range(n-1):
    print(*Ans[i])
else:    
  Ap,Az,Am=[],[],[]
  for i in range(n):
    if A[i]>0:
      Ap.append(A[i])
    elif A[i]==0:
      Az.append(A[i])
    else:
      Am.append(-A[i])
  Ap.sort()
  Am.sort()
  pp,mm=Ap.pop(),Am.pop()
  heapq.heapify(Ap)
  heapq.heapify(Am)

  while len(Am)>=1:
    am=heapq.heappop(Am)
    Ans.append([pp,-am])
    pp+=am
  while len(Ap)>=1:
    ap=heapq.heappop(Ap)
    Ans.append([-mm,ap])
    mm+=ap
  for i in range(len(Az)):
    Ans.append([pp,0])
  Ans.append([pp,-mm])
  print(pp+mm)
  for i in range(len(Ans)):
    print(*Ans[i])

Submission status: Accepted

Solution code:
N=int(input())
A=sorted([int(i) for i in input().split()])
Plus=[]
Noplus=[]
for i in A:
    if i>0:
        Plus.append(i)
    else:
        Noplus.append(i)
X=len(Plus)
Y=len(Noplus)
if Y==0:
    #全部正
    #-b1+b2+...bn
    M=sum(A)-2*min(A)
    print(M)
    tmp=A[0]
    for i in range(1,N):
        if i!=N-1:
            print(tmp,A[i])
            tmp-=A[i]
        else:
            print(A[i],tmp)
            tmp=A[i]-tmp
elif X==0:
    #全部負
    #-b1-b2-...-b(n-1)+bn
    M=-sum(A)+2*max(A)
    print(M)
    tmp=A[N-1]
    for i in range(N-1):
        print(tmp,A[i])
        tmp-=A[i]
elif X<Y:
    print(sum([abs(i) for i in A]))
    D=Y-X
    #X:+,X+D:-
    #負の方が多い
    tmp=Plus.pop()
    for i in range(D):
        tmp2=Noplus.pop()
        print(tmp,tmp2)
        tmp-=tmp2
    #Plus:X-1個,tmp
    #Noplus:Y-D-1=X個
    tmp2=Noplus.pop()
    print(tmp,tmp2)
    tmp-=tmp2
    for i in range(X-1):
        tmp2=Noplus.pop()
        print(tmp2,tmp)
        tmp=tmp2-tmp
        tmp2=Plus.pop()
        print(tmp2,tmp)
        tmp=tmp2-tmp
else:
    print(sum([abs(i) for i in A]))
    #Y<X
    D=X-Y
    #Y+D:+,Y:-
    #正の方が多い
    tmp=Noplus.pop()
    for i in range(D):
        tmp2=Plus.pop()
        print(tmp,tmp2)
        tmp-=tmp2
    #Plus:X-D=Y個
    #Noplus:Y-1個,tmp
    tmp2=Plus.pop()
    print(tmp2,tmp)
    tmp=tmp2-tmp
    for i in range(Y-1):
        tmp2=Noplus.pop()
        print(tmp2,tmp)
        tmp=tmp2-tmp
        tmp2=Plus.pop()
        print(tmp2,tmp)
        tmp=tmp2-tmp

Submission status: Accepted

Solution code:
n=int(input())
a=sorted(list(map(int,input().split())))
if a[-1]<=0:
  print(2*a[-1]-sum(a))
  s=a[-1]
  for i in a[:-1]:
    print(s,i)
    s-=i
elif a[0]>=0:
  print(sum(a)-2*a[0])
  s=a[0]
  for i in a[1:-1]:
    print(s,i)
    s-=i
  print(a[-1],s)
else:
  m=0
  for i in range(n):
    if a[i]>=0:
      k=i
      break
    m-=a[i]
  print(m+sum(a[k:]))
  s=a[0]
  for i in a[k:-1]:
    print(s,i)
    s-=i
  print(a[-1],s)
  s=a[-1]-s
  for i in a[1:k]:
    print(s,i)
    s-=i

Submission status: Accepted

Solution code:
import bisect

N=int(input())
A=[int(i) for i in input().split(" ")]
A=sorted(A)
traceback=[]

if A[0]>=0:
    minus=[A[0]]
    plus=A[1::]
elif A[-1]<=0:
    minus=A[:-1:]
    plus=[A[-1]]
else:
    index=bisect.bisect_left(A,0)
    minus=A[:index:]
    plus=A[index::]

print(sum(plus)-sum(minus))
m=minus.pop(0)
for p in plus[:-1:]:
    print(m,p)
    m=m-p
print(plus[-1],m)
p=plus[-1]-m
for m in minus:
    print(p,m)
    p=p-m

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 20:54:34 2019

@author: Yamazaki Kenichi
"""

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

A.sort()

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

if near0 != 0:
    near0 -= 1

tmp = A[near0]
T = []
for i in range(near0+1,N-1):
    T.append([tmp,A[i]])
    tmp = tmp - A[i]

T.append([A[N-1],tmp])
tmp = A[N-1] - tmp
for i in range(near0):
    T.append([tmp,A[i]])
    tmp = tmp - A[i]

print(tmp)
for t in T:
    print(' '.join(map(str,t)))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort()
if a[0] >= 0:
    print(sum(a) - 2 * min(a))
    if n == 2:
        print(a[1], a[0])
    else:
        print(a[0], a[1])
        now = a[0] - a[1]
        for i in range(2, n-1):
            print(now, a[i])
            now = now - a[i]
        print(a[-1], now)
elif a[-1] <= 0:
    print(sum(map(abs, a)) + 2 * max(a))
    b = a[::-1]
    print(b[0], b[1])
    now = b[0] - b[1]
    for i in range(2, n):
        print(now, b[i])
        now -= b[i]
else:
    print(sum(map(abs, a)))
    if n == 2:
        print(a[1], a[0])
        exit()
    hu = list(filter(lambda x: x<0, a))
    se = list(filter(lambda x: x>=0, a))
    if len(se) == 1:
        print(a[-1], a[0])
        now = a[-1] - a[0]
        for i in range(1, n-1):
            print(now, a[i])
            now = now - a[i]
    else:
        print(hu[0], se[0])
        now = hu[0] - se[0]
        for i in range(1, len(se)-1):
            print(now, se[i])
            now -= se[i]
        print(se[-1], now)
        now = se[-1] - now
        for i in range(1, len(hu)):
            print(now, hu[i])
            now -= hu[i]

Submission status: Accepted

Solution code:
import bisect
import sys

N = int(input())
A = list(map(int,input().split()))
A.sort()
ans = 0
if N == 2:
    print(str(A[1]-A[0]))
    print(str(A[1]) + " " + str(A[0]))
else:
    if A[0] <= 0 and A[-1] >= 0:
        for i in range(N):
            ans += abs(A[i])
        print(str(ans))
        boarder = bisect.bisect_left(A, 0)
        if boarder != 0 and boarder != N-1:
            print(str(A[boarder-1]) + " " + str(A[boarder]))
            x = A[boarder-1] - A[boarder]
        else:
            if boarder == N-1:
                x = A[-1]
                for i in range(N-2, -1, -1):
                    print(str(x) + " " + str(A[i]))
                    x -= A[i]
                sys.exit()
            x = 0
        for i in range(boarder+1, N-1):
            print(str(x) + " " + str(A[i]))
            x -= A[i]
        print(str(A[-1]) + " " + str(x))
        x = A[-1] - x
        for i in range(boarder-2, -1, -1):
            print(str(x) + " " + str(A[i]))
            x -= A[i]
    elif A[0] <= 0:
        print(str(abs(sum(A))+A[-1]*2))
        
        print(str(A[N-1]) + " " + str(A[N-2]))
        x = A[N-1] - A[N-2]
        for i in range(N-3, -1, -1):
            print(str(x) + " " + str(A[i]))
            x -= A[i]
        
    else:
        print(str(sum(A)-A[0]*2))

        print(str(A[0]) + " " + str(A[1]))
        x = A[0] - A[1]
        for i in range(2, N-1):
            print(str(x) + " " + str(A[i]))
            x -= A[i]
        print(str(A[-1]) + " " + str(x))

Submission status: Accepted

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

a.sort()

if a[-1] <= 0:
    print(2*a[-1]-sum(a))
    p = a[-1]
    for i in range(1,n):
        print(p,a[n-1-i])
        p -= a[n-1-i]
    exit()

#k回マイナスを使う
k = bisect.bisect_right(a,0)
if k == 0:
    print(sum(a)-2*a[0])
    p = a[0]
    for i in range(1,n-1):
        print(p,a[i])
        p -= a[i]
    print(a[-1],p)
    exit()

res = 0
for i in range(k):
    res -= a[i]
for i in range(k,n):
    res += a[i]
print(res)
p = a[0]
for i in range(k,n-1):
    print(p,a[i])
    p -= a[i]
print(a[-1],p)
p = a[-1]-p

for i in range(1,k):
    print(p,a[i])
    p -= a[i]

Submission status: Accepted

Solution code:
#C問題
N = int(input())
A = list(map(int,input().split()))
A.sort()
AMIN = A[0]
AMAX = A[-1]
anslist = []
if AMIN*AMAX < 0:
    for i in range(N-1):
        if i == 0:
            pass
        elif A[i] < 0:
            anslist.append([AMAX,A[i]])
            AMAX-=A[i]
        elif A[i] == 0:
            anslist.append([AMAX,A[i]])
        elif A[i] > 0:
            anslist.append([AMIN,A[i]])
            AMIN-=A[i]
    anslist.append([AMAX,AMIN])
    ans = (AMAX-AMIN)
elif AMIN*AMAX >= 0:
    if AMAX > 0:
        for i in range(N-1):
            if i == 0:
                pass
            elif i == 1:
                anslist.append([A[0],A[1]])
                AMIN = A[0]-A[1]
            else:
                anslist.append([AMIN,A[i]])
                AMIN-=A[i]
        anslist.append([AMAX,AMIN])
        ans = (AMAX-AMIN)
    else:
        B = []
        for i in range(N):
            B.append(-A[N-i-1])
        BMIN = B[0]
        BMAX = B[-1]
        for i in range(N-1):
            if i == 0:
                pass
            elif i == 1:
                anslist.append([-B[0],-B[1]])
                BMIN = B[0]-B[1]
            else:
                anslist.append([-BMIN,-B[i]])
                BMIN-=B[i]
        anslist.append([-BMIN,-BMAX])
        ans = (BMAX-BMIN)
        
print(ans)
for cell in anslist:
    print(cell[0],cell[1])

Submission status: Accepted

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

if a[-1] < 0:
    ans = a[-1]
    for i in range(0,n-1):
        ans = ans - a[i]
    print(ans)

    ko = a[-1]
    for i in range(0,n-1):
        print(ko,a[i])
        ko = ko-a[i]

elif a[0] < 0:
    ans = 0
    negn = 0
    for i in range(n):
        ans += abs(a[i])
        if a[i]<0:
            negn += 1
    print(ans)
    s = a[0]
    for i in range(negn , n-1):
        print(s,a[i])
        s = s-a[i]
    k = a[-1]
    for i in range(1,negn):
        print(k,a[i])
        k = k-a[i]
    print(k,s)

else:
    ans = 0
    for i in range(n):
        ans += abs(a[i])
    print(ans-2*a[0])
    m = a[0]
    for i in range(1,n-1):
        print(m,a[i])
        m = m-a[i]
    print(a[-1],m)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
AM = A.pop(0)
xy = []
if AM > 0 and A[-1] >= 0:
    p = 1
elif AM <= 0 and A[-1] < 0:
    p = 2
else:
    p = 3
if p == 1:
    while(len(A)>1):
        x = A.pop(-1)
        y = A.pop(0)
        xy.append([x, y])
        A.append(x-y)
    xy.append([AM, A[0]])
    ans = AM - A[0]
if p == 2:
    while(len(A)>1):
        x = AM
        y = A.pop(-1)
        xy.append([x, y])
        AM -= y
    xy.append([AM, A[0]])
    ans = AM - A[0]
if p == 3:
    while(len(A)>1):
        y = A.pop(0)
        if y >= 0:
            x = A.pop(-1)
            xy.append([x, y])
            A.append(x-y)
        else:
            x = AM
            xy.append([x, y])
            AM -= y
    xy.append([AM, A[0]])
    ans = AM - A[0]
print(ans)
for out in xy:
    print(*out)

Submission status: Accepted

Solution code:
import numpy as np
 
N = int(input())
*A, = map(int, input().split())

A.sort()
A = A[::-1]

log = []

a = A[0] #max
b = A[-1] #min
for i in range(1,N-1):
  if (A[i] < 0):
    log.append((a,A[i]))
    a -= A[i]
  else:
    log.append((b,A[i]))
    b -= A[i]
log.append((a,b))
print(a-b)
for l in log:
  print(l[0], l[1])

Submission status: Accepted

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


plusq =deque([a for a in A if a >=0])
minusq = deque([a for a in A if a < 0])

if not plusq:
    plusq.append(minusq.pop())
elif not minusq:
    minusq.appendleft(plusq.popleft())

ans = []

x = minusq.pop()
tmp_plus = plusq.pop()
while plusq:
    y = plusq.pop()
    ans.append((x,y))
    x = x - y

ans.append((tmp_plus,x))
x = tmp_plus  - x

while minusq:
    y = minusq.pop()
    ans.append((x,y))
    x = x - y
print(x)
for x,y in ans:
    print(x,y)

Submission status: Accepted

Solution code:
import bisect 

n=int(input())
l=list(map(int,input().split()))
l.sort()
if l[0]>=0:
    #print('hello')
    a=l[0]
    ans=0
    for i in range(n):
        ans+=l[i]
    print(ans-2*l[0])
    for i in range(1,n-1):
        print(a,l[i])
        a-=l[i]
    print(l[-1],a)
elif l[-1]<=0:
    #print('hello')
    a=l[-1]
    ans=l[-1]
    for i in range(n-1):
        ans-=l[i]
    print(ans)
    for i in range(n-1):
        print(a,l[i])
        a-=l[i]
else:
    #print('hello')
    idx=bisect.bisect(l,0)
    ans=0
    for i in range(n):
        if l[i]>=0:
            ans+=l[i]
        else:
            ans-=l[i]
    print(ans)
    a=l[0]
    for i in range(idx,n-1):
        print(a,l[i])
        a-=l[i]
    b=l[-1]
    for i in range(1,idx):
        print(b,l[i])
        b-=l[i]
        
    print(b,a)

Submission status: Accepted

Solution code:
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
# All plus
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
# All minus
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
# both of tem
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)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:

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)