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:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

a.sort()
mc = sum(item<0 for item in a)
ans = []
if mc==1 or mc==0:
    val = a[0]
    for i in range(n-2):
        ans.append((val, a[i+1]))
        val = val - a[i+1]
    ans.append((a[n-1], val))
    value = a[n-1] - val
elif mc<n:
    val = a[-1]
    for i in range(mc-1):
        ans.append((val, a[i]))
        val -= a[i]
    val2 = a[mc-1]
    for i in range(mc, n-1):
        ans.append((val2, a[i]))
        val2 -= a[i]
    ans.append((val, val2))
    value = val-val2
else:
    val = a[-1]
    for i in range(n-1):
        ans.append((val, a[i]))
        val -= a[i]
    value = val
        
print(value)
write("\n".join(" ".join(map(str, item)) for item in ans))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys


def main():
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())



    def solve(L):
        M = 0
        command = []
        if L[-1] >= 0:
            # 全て正
            if len(L) > 2:
                command.append([L[-1], L[0]])
                neg = L[-1] - L[0]
                L = L[1:-1]
                for i in range(1, len(L)):
                    command.append([neg, L[i]])
                    neg -= L[i]
                # 最後に正 - 負
                command.append([L[0], neg])
                M = L[0] - neg
            else:
                command.append([L[0], L[1]])
                M = L[0] - L[1]
        elif L[0] <= 0:
            # 全て負
            command.append([L[0], L[-1]])
            pos = L[0] - L[-1]            
            L = L[1:-1]
            for i in range(len(L)):
                command.append([pos, L[i]])
                pos -= L[i]
            M = pos
        else:
            for i in range(len(L)):
                if L[i] < 0:
                    break
            neg = L[i]
            for j in range(1, i):
                command.append([neg, L[j]])
                neg -= L[j]
            L = [L[0], neg] + L[i+1:]
            M = L[0]
            for i in range(1, len(L)):
                command.append([M, L[i]])
                M -= L[i]
        return M, command
                

    
    
    n = ii()
    L = lmi()
    L.sort(reverse=True)
    M, command = solve(L)
    print(M)
    for x, y in command:
        print(f"{x} {y}")


if __name__ == "__main__":
    main()

Submission status: Accepted

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    A=LI()
    A.sort(reverse=True)
    
    pl=A[0]#負のものはこちらから引いていく
    mi=A[-1]#正のものはこちらから引いていく
    
    ans=[]
    
    for i in range(N-2):
        a=A[i+1]
        if a>=0:
            ans.append([mi,a])
            mi-=a
        else:
            ans.append([pl,a])
            pl-=a
            
    ans.append([pl,mi])
    print(pl-mi)
    for i in range(len(ans)):
        print(' '.join(map(str, ans[i])))
    

main()

Submission status: Accepted

Solution code:
n = int(input())
mi = []
pl = []

l = list(map(int,input().split()))
for i in l:
    if i >= 0:
        pl.append(i)
    else:
        mi.append(i)
pl.sort()
mi.sort()
if n == 2:
    print(max(l)-min(l))
    print(max(l),min(l))
    exit()

if pl and mi:
    ans = []
    np = pl[-1]
    for i in range(1,len(mi)):
        ans.append([np,mi[i]])
        np -= mi[i]
    nm = mi[0]
    for i in range(len(pl)-1):
        ans.append([nm,pl[i]])
        nm -= pl[i]
    ans.append([np,nm])
    print(np-nm)
    for i in ans:
        print(*i)
elif pl:
    ans = []
    ans.append([pl[0],pl[1]])
    nm = pl[0]-pl[1]
    for i in range(2,len(pl)-1):
        ans.append([nm,pl[i]])
        nm -= pl[i]
    ans.append([pl[-1],nm])
    print(pl[-1]-nm)
    for i in ans:
        print(*i)
else:
    ans = []
    ans.append([mi[-1],mi[-2]])
    np = mi[-1]-mi[-2]
    for i in range(1,len(mi)-2):
        ans.append([np,mi[i]])
        np -= mi[i]
    ans.append([np,mi[0]])
    print(np-mi[0])
    for i in ans:
        print(*i)

Submission status: Accepted

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

a.sort()

u,d,z = 0,0,0
uu,dd = [],[]
for i in range(n):
    if a[i] > 0:
        u += 1
        uu.append(a[i])
    elif a[i] < 0:
        d += 1
        dd.append(a[i])
    else:
        z += 1
        
dd = dd[::-1]
        
ans = []
if u == 0 and d == 0:
    for i in range(z-1):
        ans.append((0,0))
    cur = 0
    
elif d == 0:
    if z != 0:
        for i in range(z-1):
            ans.append((0,0))
        cur = 0
        for i in range(u-1):
            ans.append((cur,uu[i]))
            cur -= uu[i]
        ans.append((uu[u-1],cur))
        cur = uu[u-1] - cur
    else:
        cur = uu[0]
        for i in range(u-2):
            ans.append((cur,uu[i+1]))
            cur -= uu[i+1]
        ans.append((uu[u-1],cur))
        cur = uu[u-1] - cur
        
elif u == 0:
    if z != 0:
        for i in range(z-1):
            ans.append((0,0))
        cur = 0
        for i in range(d):
            ans.append((cur,dd[i]))
            cur -= dd[i]
    
    else:
        cur = dd[0]
        for i in range(d-1):
            ans.append((cur,dd[i+1]))
            cur -= dd[i+1]
            
else:
    for i in range(z):
        ans.append((uu[0],0))
    cur1 = uu[0]
    cur2 = dd[0]
    for i in range(d-1):
        ans.append((cur1,dd[i+1]))
        cur1 -= dd[i+1]
    for i in range(u-1):
        ans.append((cur2,uu[i+1]))
        cur2 -= uu[i+1]
        
    ans.append((cur1,cur2))
    cur = cur1 - cur2
    
print(cur)
for i in ans:
    print(*i)

Submission status: Accepted

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

pos = []
neg = []
for a in A:
    if 0 <= a:
        pos.append(a)
    else:
        neg.append(a)


ans = []
if pos:
    if not neg:
        pos.sort(reverse=True)
        neg.append(pos.pop())

    while len(pos) != 1:
        x = pos.pop()
        ans.append((neg[-1], x))
        neg[-1] -= x
else:
    neg.sort()
    pos.append(neg.pop())

pos = pos[0]
while neg:
    x = neg.pop()
    ans.append((pos, x))
    pos -= x

print(pos)
for row in ans:
    print(*row)

Submission status: Accepted

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

N=[]
left,right=A.popleft(),A.pop()
for i in A:
    if i<0:
        N.append([right,i])
        right -=i
    else:
        N.append([left,i])
        left -=i
N.append([right,left])
print(right-left)
for i in N:print(*i)

Submission status: Accepted

Solution code:
n=int(input())
p,m=[],[]
z=0
for i in list(map(int,input().split())):
    if i<0:m.append(i)
    elif i==0:
        z+=1
    else:p.append(i)
if p and m:
    print(sum(p)-sum(m))
    if z:
        for h in range(z-1):
            print("0 0")
        now=0
    else:now=p.pop()
    for j in m[1:]:
        print(now,j)
        now-=j
    if p:
        print(m[0],now)
        now=-now+m[0]
        for j in p[1:]:
            print(now,j)
            now-=j
        print(p[0],now)
    else:
        print(now,m[0])
elif p:
    if z:
        print(sum(p))
        for h in  range(z-1):
            print("0 0")
        now=0
        f=p.pop()
        for i in p:
            print(now,i)
            now-=i
        print(f,now)
    else:
        print(sum(p)-2*min(p))
        p.sort()
        now=p[0]
        k=p.pop()
        for j in p[1:]:
            print(now,j)
            now-=j
        print(k,now)
else:
    if z:
        print(-sum(m))
        for h in  range(z-1):
            print("0 0")
        now=0
    else:
        m.sort()
        print(-sum(m)+2*max(m))
        now=m.pop()
    for i in m:
        print(now,i)
        now-=i

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
a.sort()
aminus = []
aplus = []
p = 0
q = 0
for i in a:
    if i >= 0:
        aplus.append(i)
        p += 1
    elif i < 0:
        aminus.append(i)
        q += 1
ans = []
cou = 0
if aplus and aminus:
    now = aminus[0]
    for i in range(p-1):
        ans.append((now,aplus[i]))
        now = now - aplus[i]
    aminus[0] = now
    now = aplus[p-1]
    for i in range(q):
        ans.append((now,aminus[i]))
        now = now - aminus[i]
    cou = now
elif aplus:
    now = aplus[0]
    for i in range(1,p-1):
        ans.append((now,aplus[i]))
        now = now - aplus[i]
    ans.append((aplus[p-1],now))
    cou = aplus[p-1] - now
elif aminus:
    now = aminus[q-1]
    for i in range(q-1):
        ans.append((now,aminus[i]))
        now = now - aminus[i]
    cou = now

print(cou)
for i in range(n-1):
    print(*ans[i])

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
p,n = 0,0
Positive,Negative = [],[]
ans = []
for i in range(N):
    if A[i] >= 0:
        p += 1
        Positive.append(A[i])
    else:
        n += 1
        Negative.append(A[i])
Positive.sort()
Negative.sort()
if n == 0:
    now = Positive[0]
    for i in range(1,N-1):
        ans.append((now,Positive[i]))
        now -= Positive[i]
    ans.append((Positive[N-1],now))
    Positive[N-1] -= now
    print(Positive[N-1])
    for i in range(len(ans)):
        print(*ans[i])
elif n >= 1 and p >= 1:
    now = Negative[0]
    for i in range(p-1):
        ans.append((now,Positive[i]))
        now -= Positive[i]
    bigM = now
    now = Positive[-1]
    for i in range(1,n):
        ans.append((now,Negative[i]))
        now -= Negative[i]
    bigP = now
    ans.append((bigP,bigM))
    bigP -= bigM
    print(bigP)
    for i in range(len(ans)):
        print(*ans[i])
else:
    now = Negative[-1]
    for i in range(N-1):
        ans.append((now,Negative[i]))
        now -= Negative[i]
    print(now)
    for i in range(len(ans)):
        print(*ans[i])

Submission status: Accepted

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

ans = []
for i in range(1, n-1):
    if a[i] <= 0:
        ans.append([a[n-1], a[i]])
        a[n-1] += abs(a[i])

    else:
        ans.append([a[0], a[i]])
        a[0] -= a[i]
        
ans.append([a[n-1], a[0]])

print(a[n-1] - a[0])
for i in range(n-1):
    print(*ans[i])

Submission status: Accepted

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

res = []
low, up = a[0], a[-1]
for i in range(1, n-1):
    if a[i] < 0:
        res.append([up, low])
        up = up - low
        low = a[i]
    else:
        res.append([low, up])
        low = low - up
        up = a[i]

print(up-low)
res.append([up, low])

for v in res:
    print(*v)

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    A = list(map(int, input().split()))
    if len(A) == 2 and 0 in A:
        print(max(A) - 0)
        print(max(A), 0)
        exit()

    plus = deque(sorted([a for a in A if a >= 0]))
    minus = deque(sorted([a for a in A if a < 0]))

    res = []
    if plus and minus:
        while len(plus) > 1:
            x = minus.pop()
            y = plus.pop()
            res.append([x, y])
            minus.append(x - y)
        while minus:
            x = plus.pop()
            y = minus.pop()
            res.append([x, y])
            plus.append(x - y)
    elif plus:
        x = plus.popleft()
        y = plus.pop()
        res.append([x, y])
        minus.append(x - y)
        while len(plus) > 1:
            x = minus.pop()
            y = plus.pop()
            res.append([x, y])
            minus.append(x - y)
        x = plus.pop()
        y = minus.pop()
        res.append([x, y])
        plus.append(x - y)
    else:
        x = minus.pop()
        y = minus.popleft()
        res.append([x, y])
        plus.append(x - y)
        while minus:
            x = plus.pop()
            y = minus.pop()
            res.append([x, y])
            plus.append(x - y)

    print(*plus)
    for i in res:
        print(*i)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

Submission status: Accepted

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

if n==2:
    print(al[1]-al[0])
    print(al[1],al[0])
    exit()

res = []
neg = []
pos = []
for a in al:
    if a>=0:
        pos.append(a)
    else:
        neg.append(a)

if len(pos)==0:
    res.append((neg[-1],neg[-2]))
    pos.append(neg[-1]-neg[-2])
    neg = neg[:-2]
if len(neg)==0:
    res.append((pos[0],pos[1]))
    neg.append(pos[0]-pos[1])
    pos = pos[2:]


# len(pos)>0 and len(neg)>0
n = neg[0]
for i in range(1,len(pos)):
    res.append((n,pos[i]))
    n = n - pos[i]
p = pos[0]
for i in range(1,len(neg)):
    res.append((p,neg[i]))
    p = p - neg[i]
res.append((p,n))
print(p-n)
for x,y in res:
    print(x,y)

Submission status: Accepted

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

b = []
c = []

for i in a:
    if i < 0:
        c.append(i)
    else:
        b.append(i)

if len(c) >= 1 and len(b) >= 1:
    while len(b) > 1:
        x = b.pop(0)
        array = [c[0], x]
        c[0] -= x
        arrays.append(array)
    while len(c) > 1:
        y = c.pop(0)
        array = [b[0], y]
        b[0] -= y
        arrays.append(array)

    array = [b[0], c[0]]
    arrays.append(array)

    print(b[0] - c[0])

elif len(b) == 0 and len(c) >= 1:
    mi = c.pop(-1)
    while len(c) > 1:
        x = c.pop(0)
        array = [mi, x]
        mi -= x
        arrays.append(array)
    array = [mi, c[0]]
    arrays.append(array)
    print(mi - c[0])


elif len(b) >= 1 and len(c) == 0:
    mi = b.pop(0)
    while len(b) > 1:
        x = b.pop(0)
        array = [mi, x]
        mi -= x
        arrays.append(array)
    array = [b[0], mi]
    arrays.append(array)
    print(b[0]-mi)


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

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
#import numpy as np
INF = float("inf")
#d = defaultdict(int)
#d = defaultdict(list)
n = int(input())
A = list(map(int,input().split()))
A.sort()
index = bisect_left(A,0)
if index == n or index == n-1:
    ans = A[n-1]
    for i in range(n-1):
        ans -= A[i]
    print(ans)
    now = A[n-1]
    for i in range(n-1):
        x = now
        y = A[i]
        print(x,y)
        now -= y
else:
    if A[index] == 0:
        ans = 0
        for i in range(index+1,n):
            ans += A[i]
        for i in range(index):
            ans -= A[i]
        print(ans)
        now = 0
        for i in range(index+1,n):
            x = now
            y = A[i]
            if i != n-1:
                print(x,y)
                now -= y
            else:
                print(y,x)
                now = y-x
        for i in range(index):
            x = now
            y = A[i]
            print(x,y)
            now -= y
    else:
        if A[0] > 0 :
            ans = -A[0]
            for i in range(1,n):
                ans += A[i]
            print(ans)
            now = A[0]
            for i in range(1,n):
                x = now
                y = A[i]
                if i == n-1:
                    print(y,x)
                else:
                    print(x,y)
                    now -= y
        else:
            ans = 0
            for i in range(index):
                ans -= A[i]
            for i in range(index,n):
                ans += A[i]
            print(ans)
            now = A[0]
            for i in range(index+1,n):
                x = now
                y = A[i]
                print(x,y)
                now -= y
            print(A[index],now)
            now = A[index] - now
            for i in range(1,index):
                x = now
                y = A[i]
                print(x,y)
                now -= y

Submission status: Accepted

Solution code:
import bisect

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

pl= []
ml = []
for a in A:
    if a >= 0: pl.append(a)
    else: ml.append(a)

pl.sort()
ml.sort()

ans = 0
ans_l = []


if pl and ml:
    ans = ml[0]
    for p in pl[1:]:
        ans_l.append((ans,p))
        ans -= p
    ans_l.append((pl[0], ans))
    ans = pl[0] - ans
    for m in ml[1:]:
        ans_l.append((ans,m))
        ans -= m

elif not pl: # only ml
    ans = ml[-1]
    for m in ml[:-1]:
        ans_l.append((ans,m))
        ans -= m

else: # only pl
    ans = pl[0]
    for p in pl[1:-1]:
        ans_l.append((ans,p))
        ans -= p
    ans_l.append((pl[-1], ans))
    ans = pl[-1] - ans

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

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    A = list(map(int,input().split()))
    neg = []
    pos = []
    for a in A:
        if a < 0:
            neg.append(a)
        else:
            pos.append(a)
    
    neg.sort()
    pos.sort()
    
    op = []
    if len(neg) == N:
        pos.append(neg[-1])
        neg.pop()
    
    if len(pos) == N:
        neg.append(pos[0])
        pos = pos[1:]
    
    for i in range(len(pos)-1):
        op.append("{0} {1}".format(neg[0], pos[i]))
        neg[0] -= pos[i]
    
    for ne in neg:
        op.append("{0} {1}".format(pos[-1], ne))
        pos[-1] -= ne
    
    printAns(pos[-1], op)

def printAns(M, op):
    print(M)
    print(*op, sep='\n')
    
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from collections import deque

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

a.sort()

if a[0] >= 0:
    m = sum(a[1:]) - a[0]
    print(m)
    p = a.pop(0)
    while len(a) > 1:
        b = a.pop(0)
        print(*[p, b])
        p -= b
    b = a.pop()
    print(*[b, p])
elif a[-1] <= 0:
    m = -sum(a[:-1])+a[-1]
    print(m)
    p = a.pop(-1)
    while len(a) > 0:
        b = a.pop(0)
        print(*[p, b])
        p -= b
else:
    mi = list(filter(lambda x: x < 0, a))
    pl = list(filter(lambda x: x >= 0, a))
    m = -sum(mi) + sum(pl)
    print(m)
    lp = pl.pop(0)
    mi = deque(mi)
    while len(pl) > 0:
        b = pl.pop()
        c = mi.pop()
        print(*[c, b])
        c -= b
        mi.append(c)
    while len(mi) > 0:
        b = mi.pop()
        print(*[lp, b])
        lp -= b

Submission status: Accepted

Solution code:
def all_pos(lst):
    for e in lst:
        if e < 0:
            return False
    return True

def all_neg(lst):
    for e in lst:
        if e > 0:
            return False
    return True

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

ans = []
M = 0
if all_pos(A):
    A.sort()
    res = A[0]
    for i in range(1, N - 1):
        ans.append((res, A[i]))
        res -= A[i]
    ans.append((A[-1], res))
    M = A[-1] - res
elif all_neg(A):
    A.sort()
    A.reverse()
    res = A[0]
    for i in range(1, N):
        ans.append((res, A[i]))
        res -= A[i]
    M = res
else:
    A.sort()
    A.reverse()
    tmp_neg = A[-1]
    tmp_pos = A[0]
    for i in range(1, len(A) - 1):
        if A[i] >= 0:
            ans.append((tmp_neg, A[i]))
            tmp_neg -= A[i]
        else:
            ans.append((tmp_pos, A[i]))
            tmp_pos -= A[i]
    ans.append((tmp_pos, tmp_neg))
    M = tmp_pos - tmp_neg
    
print(M)
for e in ans:
    print(e[0], e[1])

Submission status: Accepted

Solution code:
# C - Successive Subtraction

N = int(input())
A = list(int(a) for a in input().split())

M = []
P = []
for a in A:
    if a >= 0:
        P.append(a)
    else:
        M.append(a)

P.sort(reverse=True)
M.sort()
lenP = len(P)
lenM = len(M)    

ans = []
anssum = 0

if lenM ==0:
    if lenP >= 3:
        ans.append((P[-1], P[-2]))
        tmp = P.pop() - P.pop()
        M.append(tmp)
        lenP -= 2
    else:
        ans.append((P[-2], P[-1]))
        tmp = P.pop() - P.pop()
        tmp *= -1
        P.append(tmp)
        lenP -= 2
elif lenP ==0:
    ans.append((M[-1], M[-2]))
    tmp = M.pop() - M.pop()
    P.append(tmp)
    lenP += 1
for i in range(lenP-1):
    ans.append((M[-1], P[-1]))
    tmp = M.pop() - P.pop()
    M.append(tmp)
while M != []:
    ans.append((P[-1], M[-1]))
    tmp = P.pop() - M.pop()
    P.append(tmp)
anssum = P.pop()

print(anssum)
for i in range(len(ans)):
    print(' '.join(map(str, ans[i])))

Submission status: Accepted

Solution code:
from collections import deque
import bisect

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

    plus = []; minus = []
    for a in A:
        if a >= 0:
            plus.append(a)
        if a < 0:
            minus.append(a)
        
    plus.sort()
    minus.sort()
    plus = deque(plus)
    minus = deque(minus)

    if N == 2:
        if A[0] >= A[1]:
            ans = A[0] - A[1]
            print(ans)
            print(A[0], A[1])
        else:
            ans = A[1] - A[0]
            print(ans)
            print(A[1], A[0])
        return

    anslist = []
    if len(plus) == 0:
        stmp = minus.popleft()
        ltmp = minus.pop()
        anslist.append((ltmp, stmp))
        ans = ltmp - stmp
        plus.append(ans)
        N -= 1
    elif len(minus) == 0:
        stmp = plus.popleft()
        ltmp = plus.pop()
        anslist.append((stmp, ltmp))
        ans = stmp - ltmp
        minus.append(ans)
        N -= 1
    else:
        pass

    for _ in range(N):
        if len(minus) > 1:
            ltmp = plus.pop()
            stmp = minus.pop()
            anslist.append((ltmp, stmp))
            plus.append(ltmp - stmp)
        elif len(plus) > 1:
            ltmp = plus.popleft()
            stmp = minus.popleft()
            anslist.append((stmp, ltmp))
            minus.append(stmp - ltmp)
        else:
            ltmp = plus.popleft()
            stmp = minus.popleft()
            anslist.append((ltmp, stmp))
            ans = ltmp - stmp
            break
    print(ans)
    for s in anslist:
        print(*s)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
#import numpy as np
import math
#from fractions import Fraction
#import itertools
#from collections import deque
#import heapq
#from fractions  import gcd
#input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
M=max(a)
m=min(a)
resm=m
resM=M
c_M=False
c_m=False
ans=[]
for i in range(n):
    if a[i]==M and c_M==False:
        c_M=True
        continue
    elif a[i]==m and c_m==False:
        c_m=True
        continue
    if a[i]>0:
        ans.append((resm,a[i]))
        resm=resm-a[i]
    else:
        ans.append((resM,a[i]))
        resM=resM-a[i]
print(resM-resm)
for i in ans:
    print(*i)
print(resM,resm)

Submission status: Accepted

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

P = [x for x in A if x >= 0]
M = [x for x in A if x < 0]

if not len(P):
    P.append(A[0])
    M = M[1:]
elif not len(M):
    P.pop()
    M.append(A[-1])

print(sum(P) - sum(M))
# -
x = M[0]
for i in range(1, len(P)):
    print(x, P[i])
    x -= P[i]

# +
y = P[0]
for i in range(1, len(M)):
    print(y, M[i])
    y -= M[i]
print(y, x)

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
from collections import deque
inf = 10**18
mod = 10**9+7

n = int(input())
a = list(map(int, input().split()))
a.sort()
minnum = a[0]
maxnum = a[-1]
zind = bisect.bisect_left(a, 0)
ans = []
ansnum = maxnum
if zind == n:
    zind-=1
for i in range(1,zind):
    tmp = a[i]
    ans.append([maxnum, tmp])
    ansnum-=tmp
    maxnum-=tmp
ansnum -= minnum
if zind == 0:
    zind+=1
for i in range(zind, n-1):
    tmp = a[i]
    ans.append([minnum, tmp])
    ansnum+=tmp
    minnum-=tmp
ans.append([maxnum, minnum])
print(ansnum)
for p in ans:
    print(*p, sep = ' ')

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
ap = []; am = []
for a in A:
  if a > 0:
    ap.append(a)
  else:
    am.append(a)

if ap and am:
  print(sum(ap) - sum(am))
  ap_last = ap.pop()
  am_base = am.pop()
  while ap:
    a = ap.pop()
    print(am_base, a)
    am_base -= a
  print(ap_last, am_base)
  ap_last -= am_base
  while am:
    a = am.pop()
    print(ap_last, a)
    ap_last -= a
elif ap:
  ap.sort(reverse=True)
  ap_base = ap.pop()
  print(sum(ap) - ap_base)
  ap_last = ap.pop()
  while ap:
    a = ap.pop()
    print(ap_base, a)
    ap_base -= a
  print(ap_last, ap_base)
else:
  am.sort()
  am_base = am.pop()
  print(am_base - sum(am))
  while am:
    a = am.pop()
    print(am_base, a)
    am_base -= a

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N=int(input())
A=list(map(int,input().split()))
A.sort()
B=[x for x in A if x>=0]
C=[x for x in A if x<0]
ans=[]
if B and C:
    P=B.pop()
    M=C.pop()
    for x in B:
        ans.append((M,x))
        M-=x
    for x in C:
        ans.append((P,x))
        P-=x
    ans.append((P,M))
    P-=M
    print(P)
    for row in ans:
        print(*row)
elif B:
    M=B[0]
    P=B.pop()
    for x in B[1:]:
        ans.append((M,x))
        M-=x
    ans.append((P,M))
    P-=M
    print(P)
    for row in ans:
        print(*row)
else:
    P=C.pop()
    for x in C:
        ans.append((P,x))
        P-=x
    print(P)
    for row in ans:
        print(*row)

Submission status: Accepted

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

a.sort()
if a[0] * a[-1] <= 0:
    total = 0
    for i in a:
        total += abs(i)
    print(total)
    now = a[-1]
    for i in range(0, n - 2):
        if a[i + 1] > 0:
            print(min(a[i], now), max(a[i], now))
            now = -1 * abs(a[i] - now)
        else:
            print(now, a[i])
            now -= a[i]
    if a[-2] > 0:
        print(a[-2], now)
    else:
        print(now, a[-2])

elif a[0] > 0:
    total = sum(a) - 2 * a[0]
    print(total)
    now = a[0]
    for i in range(1, n - 1):
        print(now, a[i])
        now -= a[i]
    print(a[-1], now)

else:
    total = -1 * sum(a) + 2 * a[-1]
    print(total)
    now = a[n - 1]
    for i in range(n - 2, -1, -1):
        print(now, a[i])
        now -= a[i]

Submission status: Accepted

Solution code:
N=int(input())
plus=[]
other=[]
d=list(map(int,input().split()))
for num in d:
    if num>0:
        plus.append(num)
    else:
        other.append(num)
if len(plus)>0:
    K=len(plus)
    if K==1:
        data=[]
        ans=plus[0]
        for q in other:
            data.append((ans,q))
            ans+=abs(q)
        print(ans)
        for some in data:
            x,y=some
            print(x,y)

    else:
        data=[]
        if len(other)>=1:
            ans=other[-1]
            for some in plus[1:]:
                data.append((ans,some))
                ans-=some
            other[-1]=ans
            ans=plus[0]
            for q in other:
                data.append((ans,q))
                ans+=abs(q)
            print(ans)
            for some in data:
                x,y=some
                print(x,y)
        else:
            plus.sort()
            ans=plus[0]
            for some in plus[1:-1]:
                data.append((ans,some))
                ans-=some
            data.append((plus[-1],ans))
            ans=plus[-1]-ans
            print(ans)
            for some in data:
                x,y=some
                print(x,y)
            
elif len(plus)==0:
    other.sort(reverse=True)
    data=[]
    ans=other[0]
    for q in other[1:]:
        data.append((ans,q))
        ans+=abs(q)
    print(ans)
    for some in data:
        x,y=some
        print(x,y)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=[i for i in a if i>=0]
c=[i for i in a if i<0]
if len(b)==n:
    b.sort()
    print(-b[0]+sum(b[1:]))
    now=b[0]
    for i in range(1,n-1):
        print(now,b[i])
        now-=b[i]
    print(b[-1],now)
elif len(c)==n:
    c.sort(reverse=1)
    print(c[0]-sum(c[1:]))
    now=c[0]
    for i in range(1,n):
        print(now,c[i])
        now-=c[i]
else:
    print(sum(b)-sum(c))
    for i in range(len(b)-1):
        print(c[0],b[i])
        c[0]-=b[i]
    for i in c:
        print(b[-1],i)
        b[-1]-=i