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: Time Limit Exceeded

Solution code:
def main():

    n = int(input())
    a = list(map(int, input().split()))
    ansList = []
    ans = -10000000000

    for i in range(n):
        tmpa = []
        for j in a:
            tmpa.append(j)
        tmpaPreMax = int(tmpa.pop(i))
        tmpAnsList = []
        while len(tmpa) > 1:
            tmpa.sort()
            tmpaMax = max(tmpa)
            tmpaMin = min(tmpa)
            tmpa.remove(tmpaMax)
            tmpa.remove(tmpaMin)
            tmpAnsList.append([tmpaMin, tmpaMax])
            tmpa.append(tmpaMin - tmpaMax)

        tmpAnsList.append([tmpaPreMax, tmpa[0]])
        if ans < tmpaPreMax - tmpa[0]:
            ans = tmpaPreMax - tmpa[0]
            ansList = []
            for k in tmpAnsList:
                ansList.append(k)

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
li = list(map(int,input().split()))
ans=[]
dekai=0
tiiisai=0
for i in range(n):
    if li[i]<0:
        tiiisai+=1
    else:
        dekai+=1
while len(li)>1:
    if dekai>tiiisai:
        x=li.pop(li.index(min(li)))
        y=li.pop(li.index(max(li)))
        dekai-=1
        if x==y:
            dekai-=1
            tiiisai+=1
    else:
        x=li.pop(li.index(max(li)))
        y=li.pop(li.index(min(li)))
        tiiisai-=1
        if x==y:
            dekai-=1
            tiiisai+=1
    ans.append(str(x)+" "+str(y))
    li.append(x-y)
print(li[0])
for i in range(len(ans)):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))
#print(a)
s=a.copy()
i=2
while i!=n:
    z=min(a)-max(a)
    a.remove(min(a))
    a.remove(max(a))
    a.append(z)
    i+=1
#print(z)
#print(a)
print(max(a)-min(a))
i=2
while i!=n:
    z=min(s)-max(s)
    print(min(s)," ",max(s))
    s.remove(min(s))
    s.remove(max(s))
    s.append(z)
    i+=1
print(max(s)," ",min(s))

Submission status: Time Limit Exceeded

Solution code:
def main():

    n = int(input())
    a = list(map(int, input().split()))
    ansList = []
    ans = -10000000000

    for i in range(n):
        tmpa = []
        for j in a:
            tmpa.append(j)
        tmpaPreMax = int(tmpa.pop(i))
        tmpAnsList = []
        while len(tmpa) > 1:
            tmpa.sort()
            tmpaMax = tmpa.pop()
            tmpaMin = tmpa.pop(0)
            tmpAnsList.append([tmpaMin, tmpaMax])
            tmpa.append(tmpaMin - tmpaMax)

        tmpAnsList.append([tmpaPreMax, tmpa[0]])
        if ans < tmpaPreMax - tmpa[0]:
            ans = tmpaPreMax - tmpa[0]
            ansList = []
            for k in tmpAnsList:
                ansList.append(k)

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:

n = int(input())
a = input().split()

for i in range(len(a)):
    a[i] = int(a[i])

x = 0
y = 0

operations = []

for i in range(n-2):
    a_sorted = sorted(a)
    x = a_sorted[0]
    y = a_sorted[1]

    a.remove(x)
    a.remove(y)
    a.append(x-y)
    operations.append(str(x) + " " + str(y))
a_sorted = sorted(a)
a_sorted_reverse = sorted(a_sorted, reverse=True)
x = a_sorted_reverse[0]
a_sorted_reverse.remove(x)
a_sorted = sorted(a_sorted_reverse)
y = a_sorted[0]
operations.append(str(x) + " " + str(y))


a.remove(x)
if y in a:
    a.remove(y)
a.append(x-y)

print(sorted(a, reverse=True)[0])
for i in operations:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
ansList = []
ans = -10000000000

for i in range(n):
    tmpa = []
    for j in a:
        tmpa.append(j)
    tmpaPreMax = int(tmpa.pop(i))
    tmpAnsList = []
    while len(tmpa) > 1:
        tmpa.sort()
        tmpaMax = tmpa.pop()
        tmpaMin = tmpa.pop(0)
        tmpAnsList.append([tmpaMin, tmpaMax])
        tmpa.append(tmpaMin - tmpaMax)

    tmpAnsList.append([tmpaPreMax, tmpa[0]])
    if ans < tmpaPreMax - tmpa[0]:
        ans = tmpaPreMax - tmpa[0]
        ansList = []
        for k in tmpAnsList:
            ansList.append(k)

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

Submission status: Accepted

Solution code:
# coding: utf-8
import sys

# from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
printout = sys.stdout.write
sprint = sys.stdout.flush
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
#import math
# from itertools import product, accumulate, combinations, product
import bisect
# import numpy as np
# from copy import deepcopy
#from collections import deque
# from decimal import Decimal
# from numba import jit

INF = 1 << 50
EPS = 1e-8
mod = 998244353


def intread():
    return int(sysread())
def mapline(t=int):
    return map(t, sysread().split())
def mapread(t=int):
    return map(t, read().split())


def run():
    N, *A = mapread()
    A.sort()
    i = bisect.bisect_right(A, -EPS)
    cache = []
    if i <= N-1:
        if i < 1:
            i = 1
        ans = A[i-1]
        for k in range(i, N-1):
            cache.append((ans, A[k]))
            ans -= A[k]
        cache.append((A[N-1], ans))
        ans = A[N-1] - ans
        for k in range(0, i-1):
            cache.append((ans, A[k]))
            ans -= A[k]
        print(ans)
        for x, y in cache:
            print(f'{x} {y}')
    elif i > N-1:
        ans = A[-1]
        for i in range(N-1):
            cache.append((ans, A[i]))
            ans -= A[i]
        print(ans)
        for x, y in cache:
            print(f'{x} {y}')


if __name__ == "__main__":
    #print(math.gcd(0, 10))
    run()

Submission status: Accepted

Solution code:
from collections import *
n=int(input())
a=list(map(int,input().split()))
a.sort()
a=deque(a)
ans=[]
aa=a.pop()
tmp=a.popleft()
while a:
    t=a.popleft()
    if t<=0:
        ans.append((aa,t))
        aa-=t
    else:
        ans.append((tmp,t))
        tmp-=t
ans.append((aa,tmp))
print(aa-tmp)
for i in ans:
    print(i[0],i[1])

Submission status: Accepted

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

l,r=0,n-1
while r-l!=1:
  t=(l+r)//2
  if a[t]>0:
    r=t
  else:
    l=t
if r==n-1:
  print(-sum(a[:-1])+a[-1])
  t=a[-1]
  for i in a[:-1]:
    print(t,i)
    t-=i
else:
  print(-a[0]+sum(map(abs,a[1:-1]))+a[-1])
  for i in a[r:-1]:
    print(a[0],i)
    a[0]-=i
  for i in a[:r]:
    print(a[-1],i)
    a[-1]-=i

Submission status: Accepted

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

A.sort()
B = A[1:N-1]
amax=A[-1]
amin=A[0]

"""
a       p1
a-p1    p2
a-p1-p2 p3
として、
b a-sum(p)
で符号を入れ替え、
b-a+sum(p)    n1
b-a+sum(p)-n1 n2
とすると
b-a+sum(pos)-sum(neg)を実現できる。
bは全体で最大（Negの場合も）
aは全体で最小（Posの場合も）を選べばよい
"""
ANS = []
ind = N-2
wk = amin
while A[ind] >= 0 and ind >= 1:
  ANS.append((wk, A[ind]))
  wk -= A[ind]
  ind -= 1

ANS.append((amax, wk))
wk = amax - wk
while ind >= 1:
  ANS.append((wk, A[ind]))
  wk -= A[ind]
  ind -= 1

print(wk)
for a,b in ANS:
  print(a,b)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = sorted(list(map(int,input().split())))
    ans = []
    for i in range(1,n-1):
        if a[i]>0:
            ans.append([a[0],a[i]])
            a[0] -= a[i]
        else:
            ans.append([a[-1],a[i]])
            a[-1] -= a[i]
    ans.append([a[-1],a[0]])
    print(a[-1]-a[0])
    for x,y in ans:
        print(x,y)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = sorted(map(int, input().split()))
ans = []
for i in range(1, n - 1):
    # +
    if a[i] < 0:
        ans.append([a[-1], a[i]])
        a[-1] -= a[i]
    # -
    else:
        ans.append([a[0], a[i]])
        a[0] -= a[i]
ans.append([a[-1], a[0]])
print(a[-1] - a[0])
for x, y in ans:
    print(x, y)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
import sys
#input = sys.stdin.readline
def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())

print(A[-1] + sum(map(abs, A[1:-1])) - A[0])
for i in range(N-2, 0, -1):
  a = A[i]
  if a > 0:
    print(A[0], a)
    A[0] -= a
  else:
    print(A[-1], a)
    A[-1] -= a
print(A[-1], A[0])

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
import sys
#input = sys.stdin.readline
def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())
if A[-1] < 0:
    print(A[-1] - sum(A[:-1]))
    for i in range(N-2, -1, -1):
        print(A[-1], A[i])
        A[-1] -= A[i]
else:
    print(sum(map(abs, A[1:])) - A[0])
    for i in range(N-2, 0, -1):
        a = A[i]
        if a > 0:
            print(A[0], a)
            A[0] -= a
        else:
            print(A[-1], a)
            A[-1] -= a
    print(A[-1], A[0])

Submission status: Accepted

Solution code:
import sys


def solve():
    input = sys.stdin.readline
    N = int(input())
    A = [int(a) for a in input().split()]
    A.sort()
    DP = [[None, None] for _ in range(N)]
    DP[0][0] = -A[0]
    DP[0][1] = -10 ** 20
    for i in range(1, N):
        DP[i][0] = DP[i-1][0] - A[i]
        DP[i][1] = max(DP[i-1][1] + A[i], DP[i-1][0] + A[i])
    print(DP[N-1][1])
    flip = N
    for i in reversed(range(1, N)):
        if DP[i][1] - DP[i-1][1] != A[i]:
            flip = i
            break
    else: flip = 1
    sumA = A[0]
    for i in range(flip, N-1):
        print(sumA, A[i])
        sumA -= A[i]
    print(A[N-1], sumA)
    sumA = A[N-1] - sumA
    for i in range(1, flip):
        print(sumA, A[i])
        sumA -= A[i]

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
import sys
#input = sys.stdin.readline
def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())
if A[-1] < 0:
    print(A[-1] - sum(A[:-1]))
    for i in range(N-2, -1, -1):
        print(A[-1], A[i])
        A[-1] -= A[i]
else:
    print(sum(map(abs, A[1:])) - A[0])
    for i in range(N-2, 0, -1):
        a = A[i]
        if a > 0:
            print(A[0], a)
            A[0] -= a
        else:
            print(A[-1], a)
            A[-1] -= a
    print(A[-1], A[0])

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
a.sort()
ret = 0
method = []

ret = a[0]
d = 2
while d < n and a[-d] > 0:
  method.append((ret, a[-d]))
  ret -= a[-d]
  d += 1
method.append((a[-1], ret))
ret = a[-1] - ret
for i in range(1, n-d+1):
  method.append((ret, a[i]))
  ret -= a[i]

print(ret)
for t in method: print(*t)

Submission status: Accepted

Solution code:
from bisect import bisect_left

N = int(input())
A = list(map(int, input().split()))
A.sort()
ans = sum(abs(a) for a in A)
if A[0] >= 0:
    ans -= 2 * A[0]
elif A[-1] < 0:
    ans += 2 * A[-1]
print(ans)
nonneg_idx = bisect_left(A, 0)
if nonneg_idx == 0:
    nonneg_idx = 1
elif nonneg_idx == N:
    nonneg_idx = N - 1
acc = A[nonneg_idx - 1]
for a in A[nonneg_idx + 1 :]:
    print(acc, a)
    acc -= a
print(A[nonneg_idx], acc)
acc = A[nonneg_idx] - acc
for a in A[: nonneg_idx - 1]:
    print(acc, a)
    acc -= a

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort()
if a[0] >= 0:
    print(sum(a) - 2 * a[0])
    x, y = a[0], 0
    for i in range(n - 2):
        x -= y
        y = a[i + 1]
        print(x, y)
    x -= y
    print(a[-1], x)
elif a[-1] <= 0:
    print(-sum(a) + 2 * a[-1])
    x, y = a[-1], 0
    for i in range(n - 1):
        x -= y
        y = a[-(i + 2)]
        print(x, y)
else:
    m = 0
    c = 0
    for i in range(n):
        m += abs(a[i])
        if a[i] <= 0:
            c = i
    print(m)
    x, y = a[0], 0
    for i in range(n - 1, c + 1, -1):
        x -= y
        y = a[i]
        print(x, y)
    x -= y
    print(a[c + 1], x)
    x = a[c + 1] - x
    for i in range(1, c + 1):
        y = a[i]
        print(x, y)
        x -= y

Submission status: Accepted

Solution code:
n=int(input())
a=sorted(list(map(int,input().split())))
m=-a[0]
for i in a[1:-1]:
  if i<0:m-=i
  else:m+=i
m+=a[-1] 
print(m)
b,c=a[0],a[-1]
for i in a[1:-1]:
  if i>0:
    print(b,i)
    b-=i
  else:
    print(c,i)
    c-=i
print(c,b)

Submission status: Accepted

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

if n==2:
    print(abs(A[0]-A[1]))
    print(*A)
    exit()
A.sort()
menos=[] ; plus=[]
for i in range(len(A)):
    if A[i]<0:
        menos.append(A[i])
    else:
        plus.append(A[i])
if menos==[]:
    print(sum(plus)-plus[0]*2)
    res=plus[0]
    for i in range(n-2):
        print(res, A[i+1])
        res=res-A[i+1]
    print(A[n-1], res);exit()
        
elif plus==[]:
    print(-sum(menos)+ menos[-1]*2)
    res=menos[-1]
    for i in range(n-1):
        print(res,menos[i])
        res=res-menos[i]
    exit()
    

print(sum(plus)-sum(menos))
m=len(menos); p=len(plus)
if p==1:
    res=plus[-1]
    for i in range(n-1):
        print(res,menos[i])
        res=res-menos[i]
    exit()
if m==1:
    res=menos[0]
    for i in range(n-2):
        print(res, plus[i])
        res=res-plus[i]
    print(plus[-1], res);exit()

Q= plus[1:]+ [menos[0]]
W= menos[1:]+[plus[0]] ;#print(Q,W)

res=W[-1]
for i in range(len(W)-1):
    print(res,W[i])
    res=res-W[i]
rec=Q[-1]
for i in range(len(Q)-1):
    print(rec, Q[i])
    rec=rec-Q[i]
print(res,rec)

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int, input().split()))
A.sort()
amin = A[0]
amax = A[-1]
B = A[1:-1]
action = []
for b in B:
    if b < 0:
        action.append((amax, b))
        amax -= b
    else:
        action.append((amin, b))
        amin -= b
action.append((amax, amin))
score = amax - amin
print(score)
for x, y in action:
    print('{} {}'.format(x, y))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n=I()
lis=LI()
lis2=sorted(lis)
pm=[-1 for i in range(n)]
for i in range(n):
    if lis2[i]>=0:
        pm[i]=1
if pm[0]==1:
    pm[0]=-1
elif pm[-1]==-1:
    pm[-1]=1
ans=0
for i in range(n):
    ans=ans+pm[i]*lis2[i]
print(ans)
x=lis2[0]
for i in range(1,n-1):
    if pm[i]==1:
        print(x,lis2[i])
        x=x-lis2[i]
for i in range(1,n-1):
    if pm[i]==-1:
        print(lis2[-1],lis2[i])
        lis2[-1]=lis2[-1]-lis2[i]
print(lis2[-1],x)

Submission status: Accepted

Solution code:
from bisect import bisect

def solve():
    N = int(input())
    A = sorted(map(int,input().split()))
    if N == 2:
        res = [(max(A),min(A))]
        s = max(A)-min(A)
        return s, res

    if A[0] >= 0:
        res = []
        x = A[0]
        for a in A[1:-1]:
            res.append((x,a))
            x -= a
        res.append((A[-1],x))
        x = A[-1]-x
        return (x,res)
    if A[-1] <= 0:
        res = []
        x = A[-1]
        for a in A[:-1]:
            res.append((x,a))
            x -= a
        return (x,res)

    res = []
    p = bisect(A,0)-1
    x = A[p]
    for a in A[p+1:N-1]:
        res.append((x,a))
        x -= a
    res.append((A[-1],x))
    x = A[-1]-x
    for a in A[:p]:
        res.append((x,a))
        x -= a
    return (x,res)



s,res = solve()
print(s)
print('\n'.join(f'{a} {b}' for a,b in res))

Submission status: Accepted

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

A_plus = []
A_minus = []
for i in range(N):
    if A[i] >= 0:
        A_plus.append(A[i])
    else:
        A_minus.append(A[i])

if len(A_plus) == 0:
    A_plus.append(A_minus.pop(A_minus.index(max(A_minus))))
elif len(A_minus) == 0:
    A_minus.append(A_plus.pop(A_plus.index(min(A_plus))))
        
ans_list = []
while len(A_plus) + len(A_minus) != 1:
    if len(A_plus) <= len(A_minus):
        x = A_plus.pop(0)
        y = A_minus.pop(0)
        ans_list.append([x, y])
        A_plus.append(x-y)
    else:
        x = A_minus.pop(0)
        y = A_plus.pop(0)
        ans_list.append([x, y])
        A_minus.append(x-y)

M = A_plus[0]
print(M)
for i in range(len(ans_list)):
    print(ans_list[i][0], ans_list[i][1])

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    a.sort()
    non_negative = len(list(filter(lambda x: x >= 0, a)))
    negative = n - non_negative
    if non_negative == 0:
        negative = n - 1
        non_negative = 1
    elif negative == 0:
        negative = 1
        non_negative = n - 1
    neg_num = a[:negative]
    non_neg_num = a[-non_negative:]
    ope = []
    for nnn in non_neg_num[:-1]:
        ope.append([neg_num[0], nnn])
        neg_num[0] -= nnn
    for nn in neg_num:
        ope.append([non_neg_num[-1], nn])
        non_neg_num[-1] -= nn
    print(non_neg_num[-1])
    for i, j in ope:
        print(i, j)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys,math,collections,itertools,bisect
input = sys.stdin.readline

N=int(input())
A=sorted(list(map(int,input().split())))
process = []
for i in range(N-2):
    tmp = A.pop()
    y=A.pop()
    A.append(tmp)
    if y>=0:
        process.append([A[0],y])
        A[0]-=y
    else:
        process.append([A[-1],y])
        A[-1]-=y
process.append([A[-1],A[0]])
print(A[-1]-A[0])
for pro in process:
    print(*pro)

Submission status: Accepted

Solution code:
n,*a=map(int,open(0).read().split())

plus=[]
minus=[]
for aa in a:
    if aa>=0:
        plus.append(aa)
    else:
        minus.append(aa)

if len(plus)==n:
    plus.sort(reverse=True)
    minus.append(plus.pop())
elif len(minus)==n:
    minus.sort()
    plus.append(minus.pop())

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

xy=minus[0]
for i in range(len(plus)-1):
    print('{} {}'.format(xy,plus[i]))
    xy-=plus[i]

print('{} {}'.format(plus[-1],xy))
xy=plus[-1]-xy

for i in range(1,len(minus)):
    print('{} {}'.format(xy,minus[i]))
    xy-=minus[i]

Submission status: Accepted

Solution code:
n=int(input())

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

if n==2:
    print(max(a)-min(a))

    print(max(a),min(a))
    exit()

#+ -が最低一つ必要
#あとはどちらの符号にもできる？

a_p=[]
#a_zero=[]
a_m=[]

for aa in a:
    if aa>=0:
        a_p.append(aa)
    else:
        a_m.append(aa)

#どっちもある

ans=[]

if len(a_m)>0 and len(a_p)>0:
    if len(a_p)==1:
        tmp=a_p[0]
        for v in a_m:
            ans.append([tmp,v])
            tmp=tmp-v
    else:
        tmp=a_m[0]
        for v in a_p[1:]:
            ans.append([tmp,v])
            tmp=tmp-v
        ans.append([a_p[0],tmp])
        tmp=a_p[0]-tmp
        for v in a_m[1:]:
            ans.append([tmp,v])
            tmp=tmp-v

elif len(a_p)>0:
    a_p.sort()

    tmp=a_p[0]
    for v in a_p[2:]:
        ans.append([tmp,v])
        tmp=tmp-v
    ans.append([a_p[1],tmp])

else:
    a_m.sort(reverse=True)

    tmp=a_m[0]
    for v in a_m[1:]:
        ans.append([tmp,v])
        tmp=tmp-v


print(ans[-1][0]-ans[-1][1])
for item in ans:
    print(item[0],item[1])

Submission status: Accepted

Solution code:

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

pos = sorted([v for v in X if v >= 0])
neg = sorted([v for v in X if v < 0], reverse=True)

ans = []
if not neg:
    # neg is empty
    cnt = pos[0]
    for v in pos[1:-1]:
        ans.append((cnt, v))
        cnt -= v
    ans.append((pos[-1], cnt))
    print(pos[-1] - cnt)
elif not pos:
    # pos is empty
    cnt = neg[0]
    for v in neg[1:]:
        ans.append((cnt, v))
        cnt -= v
    print(cnt)
else:
    # neg and pos exist
    for v in pos[:-1]:
        ans.append((neg[0], v))
        neg[0] -= v

    cnt = pos[-1]
    for v in neg:
        ans.append((cnt, v))
        cnt -= v
    print(cnt)

for v in ans:
    print(*v)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    N = int(input())
    A = sorted([int(x) for x in input().strip().split()])
    maxi = max(A)
    mini = min(A)
    plus = [a for a in A[1:-1] if a >= 0]
    minus = [a for a in A[1:-1] if a < 0]
    print(maxi + sum(plus) - sum(minus) - mini)
    for p in plus:
        print(mini, p)
        mini -= p
    print(maxi, mini)
    maxi -= mini
    for m in minus:
        print(maxi, m)
        maxi -= m

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
a = list(map(int,input().split()))
a = sorted(a)
p = 0
b = 0

qp = deque([])
qn = deque([])

for i in range(n):
    b += abs(a[i])
    if a[i] < 0:
        qn.append(a[i])
        p += 1
    else:
        qp.append(a[i])
if p != 0 and p != n:
    print(b)
    for i in range(n-2):
        if len(qp) >= 2:
            x = qn.popleft()
            y = qp.popleft()
            print(x,y)
            qn.append(x-y)
        else:
            x = qn.popleft()
            y = qp.popleft()
            print(y,x)
            qp.append(y-x)
    if len(qn) == 1 and len(qp) == 1:
        x = qn.popleft()
        y = qp.popleft()
        print(y,x)
    
elif p == 0:
    print(b-2*a[0])
    x = qp.popleft()
    y = qp.pop()
    print(x,y)
    qn.append(x-y)
    for i in range(n-3):
        x = qn.popleft()
        y = qp.popleft()
        print(x,y)
        qn.append(x-y)
    if len(qp) == 1 and len(qn) == 1:
        x = qn.popleft()
        y = qp.popleft()
        print(y,x)
    
else:
    print(b-2*abs(a[-1]))
    x = qn.popleft()
    y = qn.pop()
    print(y,x)
    qp.append(y-x)
    for i in range(n-3):
        x = qn.popleft()
        y = qp.popleft()
        print(y,x)
        qp.append(y-x)
    if len(qn) == 1 and len(qp) == 1:
        x = qn.popleft()
        y = qp.popleft()
        print(y,x)

Submission status: Accepted

Solution code:
from collections import deque


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    """
    """
    N = read_int()
    B = read_ints()
    B.sort()
    A = deque(B)
    answer = []
    while len(A) > 1:
        if len(A) == 2:
            x, y = A.pop(), A.popleft()
            A.append(x-y)
        else:
            if A[-2] >= 0:
                x, y = A.popleft(), A.pop()
                A.appendleft(x-y)
            else:
                x, y = A.pop(), A.popleft()
                A.append(x-y)
        answer.append((x, y))
    print(A[0])
    for a in answer:
        print(*a)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
As = list(mapint())
As.sort()
mini = As.pop(0)
maxi = As.pop()

ans = []
for a in As:
    if a>=0:
        ans.append((mini, a))
        mini -= a
    else:
        ans.append((maxi, a))
        maxi -= a

print(maxi-mini)
for a in ans:
    print(*a)
print(maxi, mini)

Submission status: Accepted

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

from collections import deque
q = deque(A)
mn = q.popleft()
mx = q.pop()

arr = []
for a in q:
    if a >= 0:
        arr.append((mn, a))
        mn -= a
    else:
        arr.append((mx, a))
        mx -= a
arr.append((mx, mn))
print(mx - mn)
for a,b in arr:
    print(a,b)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
def main():
    N = int(input())
    A = list(map(int, input().split()))
    pos = []
    neg = []
    for i in range(N):
        if A[i] >= 0:
            pos.append(A[i])
        else:
            neg.append(A[i])
    pos.sort()
    neg.sort(reverse=True)
    
    ans = []
    if len(pos) == 0:# 負だけ
        print(-sum(neg)+2*neg[0])
        now = neg[0]
        for i in range(1,N):
            print(now,neg[i])
            now -= neg[i]
    elif len(neg) == 0:# 正だけ
        print(sum(pos)-2*pos[0])
        now = pos[0]
        for i in range(1,N-1):
            print(now,pos[i])
            now -= pos[i]
        print(pos[N-1],now)
    else:
        p = 0
        n = 1
        ans = []
        now = pos[p]
        while n < len(neg):
            ans.append((now,neg[n]))
            now -= neg[n]
            n += 1
        
        p += 1
        now2 = neg[0]
        while p < len(pos):
            ans.append((now2,pos[p]))
            now2 -= pos[p]
            p += 1
        
        ans.append((now,now2))
        print(now-now2)
        for a in ans:
            print(a[0],a[1])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())

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

a.sort()

plus_sum = a.pop(-1)
plus_memo = plus_sum
minas_sum = a.pop(0)
minas_memo = minas_sum

for aa in a:
    if 0 < aa:
        minas_sum -= aa
    else:
        plus_sum -= aa

print(plus_sum-minas_sum)

for aa in a:
    if 0 < aa:
        print(minas_memo, aa)
        minas_memo -= aa
    else:
        print(plus_memo, aa)
        plus_memo -= aa
print(plus_memo, minas_memo)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = deque(sorted(list(map(int, input().split()))))
MAX, MIN = A.pop(), A.popleft()

ans = []
while len(A):
    if A[0] < 0:
        x, y = MAX, A.popleft()
        ans.append([MAX, y])
        MAX = MAX - y
    else:
        x, y = MIN, A.popleft()
        ans.append([x, y])
        MIN = MIN - y

ans.append([MAX, MIN])
print(MAX - MIN)
for x, y in ans:
    print(x, y)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
pos, neg, zero = [], [], []

for Ai in A:
    if Ai>0:
        pos.append(Ai)
    elif Ai<0:
        neg.append(Ai)
    else:
        zero.append(0)

if len(neg)==0:
    neg += zero
else:
    pos += zero
    
ope = []

if len(pos)>0 and len(neg)>0:
    now1 = pos[0]
    
    for i in range(1, len(neg)):
        ope.append((now1, neg[i]))
        now1 -= neg[i]
    
    now2 = neg[0]
    
    for i in range(1, len(pos)):
        ope.append((now2, pos[i]))
        now2 -= pos[i]
    
    ope.append((now1, now2))
    M = now1-now2
elif len(pos)==0:
    neg.sort(reverse=True)
    now = neg[0]
    
    for i in range(1, len(neg)):
        ope.append((now, neg[i]))
        now -= neg[i]
    
    M = now
else:
    pos.sort()
    now = pos[0]
    
    for i in range(1, len(pos)-1):
        ope.append((now, pos[i]))
        now -= pos[i]
    
    ope.append((pos[-1], now))
    M = pos[-1]-now

print(M)

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

Submission status: Accepted

Solution code:
# 正整数だけ存在する場合はどうなるだろうか
# absじゃないのが味噌で、最後のyは負数だとお得
# なのでそれまでにできるだけ負の方向にデカいyを作ってみる
# 1 2 4 4 5 8 みたいなとき 1を出発点として残りは全部引いていけるので、最後ではy=1-(2+4+4+5)=-14にできる んで最後に最大値から引くことで 8-(-14)が達成可能
# 負数だけの場合
# 上記を踏まえると唯一の負数は正数で育てることができるが、複数ある場合はどうなるだろうか
# -6 -4 -3 -1 -1 みたいなとき
# 一度でも正数が作れればいいので-1-(-6-4-3-1)=13か？

# -1 1 2 のとき
# 最小値だけで正数を達成することはできない なので最後の手番までにできるだけデカい負を作って最後に引くをする
# -4 -2 -1 3 4 のとき 負数で正を作ると-1-(-2-4)=5, [3 4 5]になってしまいなんか小さくなりそう
# 負数を育てると-4-3-4=-11, -1-(-11)=10, 10-(-2)=12ができそうで、こっちのほうがいい
# 正の数が最後の1つになるまで負を太らせ、あとは負たちを正から引くことであますことなくいただける

n = int(input())
a = sorted(list(map(int, input().split())))
if n == 2:
    print(a[1] - a[0])
    print(a[1], a[0])
    exit()
ans = []
tmp = 0
if a[0] >= 0:
    tmp = a[0]
    for i in range(1, n - 1):
        ans.append(f"{tmp} {a[i]}")
        tmp -= a[i]
    ans.append(f"{a[-1]} {tmp}")
    tmp = a[-1] - tmp
elif a[-1] <= 0:
    tmp = a[-1]
    for i in range(n - 2, -1, -1):
        ans.append(f"{tmp} {a[i]}")
        tmp -= a[i]
else:
    ok, ng = 0, n
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if a[mid] < 0:
            ok = mid
        else:
            ng = mid
    plus = a[ok + 1:]
    minus = a[:ok + 1]
    tmp = minus[0]
    idx = 0
    while idx < len(plus) - 1:
        ans.append(f"{tmp} {plus[idx]}")
        tmp -= plus[idx]
        idx += 1
    ans.append(f"{plus[idx]} {tmp}")
    tmp = plus[idx] - tmp
    for i in range(1, len(minus)):
        ans.append(f"{tmp} {minus[i]}")
        tmp -= minus[i]

print(tmp)
for av in ans:
    print(av)

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
nb = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===


def main():
    n = ni()
    a = na()

    min_n = min(a)
    max_n = max(a)
    minflg = True
    maxflg = True

    d = []
    for ai in a:
        if ai == min_n and minflg:
            minflg = False
            continue
        if ai == max_n and maxflg:
            maxflg = False
            continue
        d.append(ai)

    ans = []
    for ai in d:
        if ai < 0:
            ans.append([max_n, ai])
            max_n -= ai
        else:
            ans.append(([min_n, ai]))
            min_n -= ai
    ans.append([max_n, min_n])

    print(max_n - min_n)

    for a, b in ans:
        print(a, b)


if __name__ == '__main__':
    main()