Problem:


Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0



Sample input:
3
1 -1 2


Sample output:
4
-1 1
2 -2

Submission status: Accepted

Solution code:
N = int(input())
AA = list(map(int,input().split()))#0を含む可能性あり

A = []
count = 0
for i in range(N):
    if AA[i] != 0:
        A.append(AA[i])
    else:
        count += 1

NN = N - count
B = [abs(A[i]) for i in range(NN)]

if count == 0:
    det = 1
    s = A[0]//B[0]#最初のやつの符号
    for i in range(1,NN):
        if s * A[i] < 0:
            det = -1
            break

    if det == 1:#全て同符号
        m = min(B)

        M = sum(B) - 2 * m
        print(M)

        for i in range(NN):
            if m == B[i]:
                p = i
                break

        C = [A[i]//B[i] for i in range(NN)]

        C[p] *= -1

    else:#異符号が含まれる
        M = sum(B)
        print(M)
        C = [A[i]//B[i] for i in range(NN)]

    fp = -1 #firstplus
    fm = -1 #firstminus
    for i in range(NN):
        if fp == -1 and C[i] == 1:
            fp = i
        elif fm == -1 and C[i] == -1:
            fm = i
        elif fp != -1 and fm != -1:
            break

    X = []
    Y = []

    for i in range(NN):
        if i == fp or i == fm:
            continue
        if C[i] == -1:
            X.append(i)
        else:
            Y.append(i)

    x = A[fp]
    for i in X:
        print(x,A[i])
        x -= A[i]

    y = A[fm]
    for i in Y:
        print(y,A[i])
        y -= A[i]

    print(x,y)

elif A == []:
    print(0)
    for i in range(count-1):
        print(0,0)

else:

    det = 1
    s = A[0]//B[0]#最初のやつの符号
    for i in range(1,NN):
        if s * A[i] < 0:
            det = -1
            break

    M = sum(B)
    print(M)

    if det == 1:#全て同符号
        #これがまずい
        if s < 0:
            for i in range(count-1):
                print(0,0)
            x = 0
            for i in range(NN):
                print(x,A[i])
                x -= A[i]
        else:
            for i in range(count-1):
                print(0,0)
            x = 0
            for i in range(NN-1):
                print(x,A[i])
                x -= A[i]
            print(A[NN-1],x)
            




    else:#異符号が含まれる
        #こちらは今まで通り処理して最後に0を引きまくれば良い
        
        C = [A[i]//B[i] for i in range(NN)]

        fp = -1 #firstplus
        fm = -1 #firstminus
        for i in range(NN):
            if fp == -1 and C[i] == 1:
                fp = i
            elif fm == -1 and C[i] == -1:
                fm = i
            elif fp != -1 and fm != -1:
               break

        X = []
        Y = []

        for i in range(NN):
            if i == fp or i == fm:
                continue
            if C[i] == -1:
                X.append(i)
            else:
                Y.append(i)

        x = A[fp]
        for i in X:
            print(x,A[i])
            x -= A[i]

        y = A[fm]
        for i in Y:
            print(y,A[i])
            y -= A[i]

        print(x,y)

        for i in range(count):
            print(x-y,0)

Submission status: Accepted

Solution code:
import bisect
n=int(input())
a=list(map(int,input().split()))
a.sort()
f = bisect.bisect_left(a,0)
res = []
if f == 0:
    t = a[0]
    for i in range(1,n-1):
        res.append([t,a[i]])
        t = t - a[i]
    res.append([a[n-1],t])
    t = a[n-1] - t
elif f == n:
    t = a[n-1]
    for i in range(n-1):
        res.append([t,a[i]])
        t = t - a[i]
else:
    t = a[f-1]
    for i in range(f+1,n):
        res.append([t,a[i]])
        t = t - a[i]
    res.append([a[f],t])
    t = a[f] - t
    for i in range(f-1):
        res.append([t,a[i]])
        t = t - a[i]
    

print(t)
for sres in res:
    print(" ".join(map(str, sres)))

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, deque
import bisect
from heapq import *
from math import factorial, ceil, floor
from collections import defaultdict
sys.setrecursionlimit(200000)
input = sys.stdin.readline

# N, M, = map(int, input().split())
# N = int(input())
# L = [int(v) for v in input().split()]
# L = [[int(v) for v in input().split()] for _ in range(N)]
# L = [int(input()) for _ in range(N)]
# L = [list(input().strip())  for _ in range(N)]
# S = input().strip()

N, = map(int, input().split())
L = [int(v) for v in input().split()]
L.sort()

# only + 2
# only - 1
# + - 3
c = 0
for v in L:
    if v < 0:
        c = c | 1
    elif v > 0:
        c = c | 2

if c == 0:
    c = 2

if c == 2:
    if N == 2:
        print(max(L) - min(L))
        print(max(L), min(L))
        exit()

    ans = []
    p = L[0] - L[-1]
    ans.append((L[0], L[-1]))
    for v in L[1:-2]:
        ans.append((p, v))
        p -= v
    ans.append((L[-2], p))
    print(L[-2] - p)
    for x, y in ans:
        print(x, y)

if c == 1:
    if N == 2:
        print(max(L) - min(L))
        print(max(L), min(L))
        exit()

    ans = []
    p = L[-1] - L[0]
    ans.append((L[-1], L[0]))
    for v in L[1:-2]:
        ans.append((p, v))
        p -= v
    ans.append((p, L[-2]))
    print(p - L[-2])
    for x, y in ans:
        print(x, y)

if c == 3:
    if N == 2:
        print(max(L) - min(L))
        print(max(L), min(L))
        exit()

    mc = 0
    for v in L:
        if v < 0:
            mc += 1

    ans = []
    if N - mc == 1:
        p = L[-1] - L[0]
        ans.append((L[-1], L[0]))
        for v in L[1:-1]:
            ans.append((p, v))
            p -= v
        print(p)
        for x, y in ans:
            print(x, y)

        exit()

    ans = []
    p = L[0] - L[-1]
    ans.append((L[0], L[-1]))
    for v in L[mc:-2]:
        ans.append((p, v))
        p -= v
    ans.append((L[-2], p))
    p = L[-2] - p
    for v in L[1:mc]:
        ans.append((p, v))
        p -= v
    print(p)
    for x, y in ans:
        print(x, y)

Submission status: Accepted

Solution code:
N = int(input())

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

A.sort()

npl = A[-1]
nmi = A[0]

del A[0]
del A[-1]
lis = []

for i in A:

    if i < 0:
        lis.append([npl,i])
        npl -= i

    else:
        lis.append([nmi,i])
        nmi -= i

lis.append([npl,nmi])
print (npl-nmi)

for i in lis:

    print (i[0],i[1])

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/diverta2019-2/tasks/diverta2019_2_c

# 重要な性質: Aの各要素には好きな符号をつけるように構成できる。ただしすべて+or-はむり
# つまり負数なら-をつけ、正数ならそのまま

# 正にすべてプラスを付ける方法→負数を一つ借りて、正を引いてひって、最後に符号を逆転
# 負数に-を付ける方法→ただ引くだけで良い


# すべて負or正のときに注意して実装
N = int(input())
A = list(map(int, input().split()))

A.sort()


if A[0] >= 0:  # もし全要素が正数なら
    now = A[0]
    ansls = []
    for a in A[1:-1]:
        ansls.append((now, a))
        now = now - a

    ansls.append((A[-1], now))
    ans = A[-1] - now
    print(ans)
    for ans in ansls:
        print(*ans)
elif A[-1] <= 0:  # もし全要素が負数なら
    A = A[::-1]
    now = A[0]
    ansls = []
    for a in A[1:]:
        ansls.append((now, a))
        now = now - a

    print(now)
    for ans in ansls:
        print(*ans)
else:  # 正負が混在するならば好きに作れる
    ans = sum([abs(a) for a in A])
    print(ans)
    from bisect import bisect_right
    idx = bisect_right(A, 0) - 1  # ギリ負数を指す

    now = A[idx]
    ansls = []
    # 正の最善戦略
    for a in A[idx + 1:-1]:
        ansls.append((now, a))
        now = now - a
    ansls.append((A[-1], now))
    now = A[-1] - now  # ためていた符号大反転

    # print('-')
    # 続いて負の最善戦略
    for a in A[:idx]:
        ansls.append((now, a))
        now = now - a
    assert now == ans

    for ans in ansls:
        print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int,input().split()))

a, b = max(A), min(A)
for t in [a, b]:
    for i in range(len(A)):
        if A[i] == t:
            A.pop(i)
            break

ans = a-b
for i in range(n-2):
    ans += abs(A[i])
print(ans)

for i in range(n-2):
    if A[i] > 0:
        print(b, A[i])
        b -= A[i]
    else:
        print(a, A[i])
        a -= A[i]
print(a, b)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(lambda x:abs(x),A))

A.sort()
for i in range(N):
    if A[i]>0:
        break
hu=A[:i]
sei=A[i:]

l=[]
if sei and hu:
    ans=sei.pop(-1)
    for item in sei:
        l.append([hu[0],item])
        hu[0]-=item
    for item in hu:
        l.append([ans,item])
        ans-=item

elif sei:
    ans=sei.pop(-1)
    for i in range(len(sei)-1):
        l.append([sei[0],sei[i+1]])
        sei[0]-=sei[i+1]
    l.append([ans,sei[0]])
    ans-=sei[0]
elif hu:
    for i in range(len(hu)-1):
        l.append([hu[-1],hu[-i-2]])
        hu[-1]-=hu[-i-2]
    ans=hu[-1]

print(ans)
for item in l:
    print(*item)

Submission status: Accepted

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

answer = []
if len(set(A)) == 1: #全て同じ
  if A[0] >= 0:
    for i in range(2, N):
      answer.append((A[1], A[i]))
      A[1] -= A[i]
    answer.append((A[0], A[1]))
    answer_A = A[0] - A[1]
  else:
    for i in range(1, N):
      answer.append((A[0], A[i]))
      A[0] -= A[i]
    answer_A = A[0]
else:
  max_A = max(A)
  min_A = min(A)
  for i in range(N):
    if A[i] == max_A:
      max_i = i
    if A[i] == min_A:
      min_i = i
  for i in range(N):
    if i != max_i and i != min_i:
      if A[i] >= 0:
        answer.append((A[min_i], A[i]))
        A[min_i] -= A[i]
      else:
        answer.append((A[max_i], A[i]))
        A[max_i] -= A[i]
  answer.append((A[max_i], A[min_i]))
  answer_A = A[max_i] - A[min_i]

print(answer_A)
for a in answer:
  print(*a)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
A.sort()
flag=[0]*N
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]])
M=A[-1]-A[0]
print(M)
for u in ans:
    print(*u)

Submission status: Accepted

Solution code:
N = int(input())
A = sorted([int(i) for i in input().split()])

if max(A) < 0:
    print(max(A)-sum(A[:-1]))
    c = max(A)
    for i in range(N-1):
        print(c, A[i])
        c -= A[i]

elif min(A) >= 0:
    print(sum(A[1:])-min(A))
    c = min(A)
    for i in range(1, N-1):
        print(c, A[i])
        c -= A[i]
    print(max(A), c)

else:
    print(sum(abs(x) for x in A))
    c = min(A)
    d = max(A)
    for i in range(1, N-1):
        if A[i] < 0:
            print(d, A[i])
            d -= A[i]
        else:
            print(c, A[i])
            c -= A[i]
    print(d, c)

Submission status: Accepted

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


def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    import collections
    D = collections.deque(A)
    ans = []
    for i in range(N-1):
        a, b = D.popleft(), D.pop()
        if not D or D[-1] < 0:
            D.append(b - a)
            ans.append((b, a))
        else:
            D.appendleft(a - b)
            ans.append((a, b))
    print(D.pop())
    for x, y in ans:
        print(x, y)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

left = a.popleft()
right = a.pop()

ans = []
for i in a:
    if i > 0:
        ans.append((left, i))
        left -= i
    else:
        ans.append((right, i))
        right -= i
else:
    ans.append((right, left))

print(right-left)
for x, y in ans:
    print(x, y)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
read = sys.stdin.read

N, *A = map(int, read().split())
A.sort()
zero = bisect_left(A, 0)
xy = []
minimum = A[0]
maximum = A[-1]
for i in range(1, N - 1):
    if i < zero:
        xy.append(str(maximum) + ' ' + str(A[i]))
        maximum -= A[i]
    else:
        xy.append((str(minimum) + ' ' + str(A[i])))
        minimum -= A[i]
else:
    xy.append(str(maximum) + ' ' + str(minimum))

print(maximum - minimum)
print('\n'.join(xy))

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
read = sys.stdin.read

N, *A = map(int, read().split())
A.sort()
zero = bisect_left(A, 0)
xy = []
for i in range(1, N - 1):
    if i < zero:
        xy.append((A[-1], A[i]))
        A[-1] -= A[i]
    else:
        xy.append((A[0], A[i]))
        A[0] -= A[i]

print(A[-1] - A[0])
for x, y in xy:
    print(x, y)
print(A[-1], A[0])

Submission status: Accepted

Solution code:
def examC():
    N = I()
    A = LI()
    negative = []; positive = []
    ans = 0; ansC = []
    for i in A:
        if i<0:
            negative.append(i)
        else:
            positive.append(i)
    if negative==[]:
        positive.sort()
        if N>2:
            cur = positive[0] - positive[1]
            ansC.append([positive[0], positive[1]])
            ans = sum(positive) - 2 * positive[0]
            for i in range(2, N - 1):
                ansC.append([cur, positive[i]])
                cur -= positive[i]
            ansC.append([positive[N - 1], cur])
        else:
            ansC.append([positive[1],positive[0]])
            ans = positive[1]-positive[0]

    elif positive==[]:
        negative.sort(reverse=True)
        cur = negative[0] - negative[1]
        ansC.append([negative[0],negative[1]])
        ans = -sum(negative)+2*negative[0]
        for i in range(2,N):
            ansC.append([cur,negative[i]])
            cur -=negative[i]
    else:
        positive.sort()
        negative.sort(reverse=True)
        ans = sum(positive) - sum(negative)
        curN = negative[0]
        curP = positive[0]
        for i in range(len(positive)-1):
            ansC.append([curN,positive[i+1]])
            curN -=positive[i+1]
        for i in range(len(negative)-1):
            ansC.append([curP,negative[i+1]])
            curP -=negative[i+1]
        ansC.append([curP,curN])

    print(ans)
    for v in ansC:
        print(" ".join(map(str,v)))

from string import digits
import sys,copy,bisect,itertools,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')

examC()

Submission status: Accepted

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

S = sum(map(abs,A))

if all([a>0 for a in A]):
    print(S-2*min(A))
    A = sorted(A)
    B = [A[0]]
    for i in range(1,N):
        B.append(B[-1]-A[i])
    for i in range(N-2):
        print(B[i],A[i+1])
    print(A[N-1],B[N-2])

elif all([a<0 for a in A]):
    print(S+2*max(A))
    A = sorted(A)
    B = [A[-1]]
    for i in range(N-1):
        B.append(B[-1]-A[i])
    for i in range(N-1):
        print(B[i],A[i])

else:
    print(S)
    A = sorted(A)
    B = [A[0]]
    for i in range(N):
        if N-1-2-i<0 or A[-2-i]<0:
            print(A[-1-i],B[-1])
            B.append(A[-1-i]-B[-1])
            break
        print(B[-1],A[-1-i])
        B.append(B[-1]-A[-1-i])
    C = [B[-1]]
    for i in range(1,N):
        if A[i]>=0:
            break
        print(C[-1],A[i])
        C.append(C[-1]-A[i])

Submission status: Accepted

Solution code:
import bisect
N = int(input())
A = list(map(int,input().split()))
if N == 2:
  print(max(A)-min(A))
  print(*A)
  exit()
A.sort()
#print(A)
plus = []
minus = []
for i in range(N):
  if A[i] < 0:
    minus.append(A[i])
  else:
    plus.append(A[i])
minus.sort()
plus.sort()
if len(plus) == 0:
  plus.append(minus.pop(-1))
elif len(minus) == 0:
  minus.append(plus.pop(0))
#print(plus)
#print(minus)
tmp = plus[-1]
tmp2 = minus[-1]
ans = []
cnt = 0
for i in range(len(plus)-1):
  ans.append([tmp2,plus[i]])
  tmp2 -= plus[i]
minus[-1] = tmp2
for i in range(len(minus)):
  ans.append([tmp,minus[i]])
  tmp -= minus[i]
print(tmp)
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()
B=[A[i] for i in reversed(range(N)) if A[i]<0]
C=[A[i] for i in range(N) if A[i]>=0]
s=0
if len(B)>0 and len(C)>0:
  s=sum(B)*-1
  s+=sum(C)
else:
  if len(B)>0:
    s=B[0]-(sum(B)-B[0])
  else:
    s=sum(C)-C[0]*2
print(s)
tmp=0
if len(B)==0:
  tmp=C[0]
  for i in range(2,len(C)):
    print(tmp,C[i])
    tmp-=C[i]
  print(C[1],tmp)
  
  
elif len(C)==0:
  tmp=B[0]
  for i in range(1,len(B)):
    print(tmp,B[i])
    tmp-=B[i]
else:
  tmp=C[0]
  tmp2=B[0]
  for i in range(1,len(B)):
    print(tmp,B[i])
    tmp-=B[i]
  for i in range(1,len(C)):
    print(tmp2,C[i])
    tmp2-=C[i]
  print(tmp,tmp2)
  tmp-=tmp2

Submission status: Accepted

Solution code:
#12:17
n = int(input())
a = list(map(int,input().split()))
plus = []
minus = []
for i in range(n):
  if a[i] >= 0:
    plus.append(a[i])
  else:
    minus.append(a[i])
plus.sort()
minus.sort(reverse=True)
lp = len(plus)
lm = len(minus)
if lp >= 1 and lm >= 1:
  ans = sum(plus) - sum(minus)
  print(ans)
  x = minus[0]
  lp = len(plus)
  for i in range(1,lp):
    print(x,plus[i])
    x = x - plus[i]
  minus[0] = x
  x = plus[0]
  for j in range(lm):
    print(x,minus[j])
    x = x - minus[j]
elif lp == 0:
  ans = - sum(minus) + 2 * max(minus)
  print(ans)
  x = minus[1]
  for j in range(2,lm):
    print(x,minus[j])
    x = x - minus[j]
  print(x,minus[0])
elif lm == 0:
  ans = sum(plus) - 2 * min(plus)
  print(ans)
  x = plus[0]
  for i in range(2,lp):
    print(x,plus[i])
    x = x - plus[i]
  print(plus[1],x)

Submission status: Accepted

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

if A[0] < 0 and A[-1] > 0:
    ans = 0
    for a in A:
        ans += abs(a)
    print(ans)
    now = A[0]
    for a in A[1:N - 1]:
        if a >= 0:
            print(now, a)
            now -= a
    print(A[-1], now)
    now = A[-1] - now
    for a in A[1: -1]:
        if a < 0:
            print(now, a)
            now -= a
elif A[0] >= 0:
    ans = sum(A) - A[0] * 2
    print(ans)
    now = A[0]
    for a in A[1: -1]:
        print(now, a)
        now -= a
    print(A[-1], now)
else:
    ans = -sum(A) + A[-1] * 2
    print(ans)
    now = A[-1]
    for a in A[: -1]:
        print(now, a)
        now -= a

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    n, k = LI()
    a = n - k
    if k == 1:
        print(0)
        return
    print(a)
    return

#B
def B():
    n = II()
    xy = LIR(n)
    if n == 1:
        print(1)
        return
    ans = inf
    for i in range(n):
        for k in range(n):
            if i != k:
                b = 1
                check = []
                check.append((i,k))
                p = xy[i][0] - xy[k][0]
                q = xy[i][1] - xy[k][1] 
                for l in range(n):
                    for m in range(n):
                        if not((l,m) in check) and p == xy[l][0] - xy[m][0] and q == xy[l][1] - xy[m][1]:
                            b += 1
                            check.append((l, m))
                ans = min(ans, n-b)
    print(ans)

    return

#C
def C():
    n = II()
    a = LI()
    a.sort(key=abs)
    ans = deque()
    positive = deque()
    negative = deque()
    for i in range(n):
        if a[i] >= 0:
            positive.append(a[i])
        else:
            negative.append(a[i])
    a = deque(a)
    lenp = len(positive)
    lenn = len(negative)
    if lenp == 0:
        for i in range(n - 1):
            b, c = a.popleft(), a.popleft()
            ans.append((b, c))
            b -= c
            a.appendleft(b)
        print(b)
    elif lenn == 0:
        for i in range(n - 2):
            b, c = a.popleft(), a.popleft()
            ans.append((b, c))
            b -= c
            a.appendleft(b)
        b, c = a.popleft(), a.popleft()
        ans.append((c, b))
        c -= b
        print(c)
    else:
        p = positive.popleft()
        negative.appendleft(p)
        for i in range(lenn - 1):
            b, c = negative.popleft(), negative.popleft()
            ans.append((b, c))
            b -= c
            negative.appendleft(b)
        p, c = negative.popleft(), negative.popleft()
        positive.appendleft(c)
        for i in range(lenp - 1):
            b, c = positive.popleft(), positive.popleft()
            ans.append((b, c))
            b -= c
            positive.appendleft(b)
        b = positive.popleft()
        ans.append((p, b))
        p -= b
        print(p)
    for an in ans:
        print(" ".join(map(str, an)))
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    C()

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    plus = []
    minus = []
    for i in a:
        if i > 0:
            plus.append(i)
        elif i < 0:
            minus.append(i)
        else:
            if len(minus) == 0:
                minus.append(i)
            else:
                plus.append(i)
    plus.sort(reverse=True)
    minus.sort()
    if len(minus) == 0:
        minus.append(plus.pop())
    elif len(plus) == 0:
        plus.append(minus.pop())
    print(sum(plus)-sum(minus))
    now = minus[-1]
    for i in range(len(plus) - 1):
        print(now, plus[i])
        now -= plus[i]
    print(plus[-1], now)
    now = plus[-1] - now
    for i in range(len(minus) - 1):
        print(now, minus[i])
        now -= minus[i]
main()

Submission status: Accepted

Solution code:
import sys
n = int(input())
a_ls = [int(i) for i in sys.stdin.readline().split()]
a_ls.sort()
flg = True
if a_ls[-1] < 0:
    score = - sum(a_ls) + a_ls[-1] * 2
    flg = False
elif a_ls[1] < 0:
    score = sum([abs(a) for a in a_ls])
else:
    score = sum(a_ls) - a_ls[0] * 2
cur = a_ls[0]
last = a_ls[-1]
print(score)
if flg:
    for i in range(1,n):
        a = a_ls[i]
        if a < 0:
            print(last, a)
            last -= a
            continue
        if i < n - 1:
            print(cur, a_ls[i])
            cur -= a_ls[i]
        else:
            print(last, cur)
else:
    for i in range(n-1):
        print(last, a_ls[i])
        last -= a_ls[i]

Submission status: Accepted

Solution code:
n = int(input())
data = list(map(int, input().split()))
data.sort()
#全て正の時の処理
if data[0] > 0:
    print(sum(data) - data[0] * 2)
    k = data[0]
    for i in range(1,n - 1):
        print("{} {}".format(k, data[i]))
        k -= data[i]
    print("{} {}".format(data[-1], k))
#すべて負の場合の処理
elif data[-1] <= 0:
    print(-sum(data) + (data[-1] * 2))
    k = data[-1]
    for i in range(n - 1):
        print("{} {}".format(k, data[i]))
        k -= data[i]
#それ以外
else: 
    print(sum(list(map(lambda x:abs(x), data))))
    max_data = data[-1]
    min_data = data[0]
    i = 1
    while data[i] <= 0:
        print("{} {}".format(max_data,data[i]))
        max_data -= data[i]
        i += 1
    while i < n - 1:
        print("{} {}".format(min_data, data[i]))
        min_data -= data[i]
        i += 1
    print("{} {}".format(max_data, min_data))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
ans = []
A.sort()
a = A.pop(0)
b = A.pop()
N -= 2
k = 1
for i in range(N):
    y = A.pop()
    if y<0:k=0
    if k:
        ans.append([a,y])
        a -= y
    else:
        ans.append([b,y])
        b -= y
ans.append([b,a])
print(b-a)
for a in ans: print(*a)

Submission status: Accepted

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
A = [int(x) for x in stdin.readline().rstrip().split()]
A.sort()
ans = []
p = A[0]
q = A[-1]
for i in A[1:-1]:
    if i < 0:
        ans.append((q,i))
        q -= i
    else:
        ans.append((p,i))
        p -= i
ans.append((q,p))
print(q-p)
for i,j in ans:
    print(i,j)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = sorted(list(map(int,input().split())))
A = deque(A)
C = []
while len(A)>1 and A[-1]<=0:
    a = A.pop()
    b = A.pop()
    C.append((a,b))
    A.append(a-b)
if len(A)==1:
    x = A[0]
else:
    B = deque(list(A)[:-1])
    while B[-1]>0:
        a = B.popleft()
        b = B.pop()
        C.append((a,b))
        B.appendleft(a-b)
    B.append(A[-1])
    while len(B)>1:
        a = B.pop()
        b = B.popleft()
        C.append((a,b))
        B.append(a-b)
    x = B[0]
print(x)
for i in range(N-1):
    print(C[i][0],C[i][1])

Submission status: Accepted

Solution code:
n=int(input())
a=[int(j) for j in input().split()]
a.sort()
ans=[]
p=a[0]
q=a[-1]
for i in a[1:-1]:
    if i<0:
        ans.append([q,i])
        q-=i
    else:
        ans.append([p,i])
        p-=i
ans.append([q,p])
print(q-p)
for i,j in ans:
    print(i,j)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
hu=0
for b in a:
    if b<0:
        hu+=1
    else:
        break
if hu==0:
    hu=1
if hu==n:
    hu=n-1
ansl=[]
nowl=a[0]
for i in range(hu,n-1):
    ansl.append((nowl,a[i]))
    nowl-=a[i]

nowr=a[n-1]
for i in range(1,hu):
    ansl.append((nowr,a[i]))
    nowr-=a[i]

ansl.append((nowr,nowl))
print(nowr-nowl)
for i in range(n-1):
    x,y=ansl[i]
    print(x,y)

Submission status: Accepted

Solution code:
N = int(input())

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

A.sort()

npl = A[-1]
nmi = A[0]

del A[0]
del A[-1]
lis = []

for i in A:

    if i < 0:
        lis.append([npl,i])
        npl -= i

    else:
        lis.append([nmi,i])
        nmi -= i

lis.append([npl,nmi])
print (npl-nmi)

for i in lis:

    print (i[0],i[1])

Submission status: Accepted

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

a.sort(reverse=True)
ans = []
for i in range(n):
    if i == 0:
        tmp = a[i]
    elif 1 <= i < n - 1:
        if a[i] > 0:
            ans.append(str(a[-1]) + ' ' +  str(a[i]))
            a[-1] -= a[i]
        else:
            ans.append(str(tmp) + ' ' +  str(a[i]))
            tmp -= a[i]
    else:
        ans.append(str(tmp) + ' ' +  str(a[-1]))
        a = tmp - a[-1]
        print(a)

for i in range(len(ans)):
    x, y = map(int, ans[i].split())
    print(x, y)

Submission status: Accepted

Solution code:
n = int(input())
arr = sorted(list(map(int,input().split())))
ans = 0
ok1 = False
ok2 = False
for i in arr:
    if i > 0:
        ok1 = True
    else:
        ok2 = True
if ok1 and ok2:
    for i in arr:
        ans += i if i > 0 else -i
    print(ans)
    ope1 = arr.pop()
    ope2 = arr.pop(0)
    for a in arr:
        if a > 0:
            print(ope2,a)
            ope2 -= a
        else:
            print(ope1,a)
            ope1 -= a
    print(ope1,ope2)
else:
    if ok1:
        ans = sum(arr) - 2*arr[0]
        print(ans)
        ope1 = arr.pop(0)
        for i in range(n-2):
            print(ope1,arr[i])
            ope1 -= arr[i]
        print(arr[-1],ope1)
    else:
        ans = -sum(arr) + 2*arr[-1]
        print(ans)
        ope2 = arr.pop(-1)
        for i in range(n-1):
            print(ope2,arr[i])
            ope2 -= arr[i]

Submission status: Accepted

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


def main():
    n = int(input())
    a = sorted(list(map(int, input().split())))
    plus = [a[-1]]
    minus = [a[0]]

    # KeyInsight
    # 具体的な数字ではなく，変数として扱う
    # 数列のうち，1つは正，もう一つは負として扱う
    # 残りは，正の値となるように符号を調整
    # See:
    # https://www.youtube.com/watch?v=TbobvdA6AlE
    for ai in a[1:-1]:
        if ai >= 0:
            plus.append(ai)
        else:
            minus.append(ai)

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

    # 正として扱う要素を1つ以外，操作(x - y)を行う
    for p in plus[1:]:
        print(minus[-1], p)
        minus[-1] -= p

    for m in minus:
        print(plus[0], m)
        plus[0] -= m


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

N = int(input())
L = list(map(int, input().split()))
L = sorted(L)
sum_L = sum(L)
N_neg = bisect.bisect_left(L, 0)
process = []
if N_neg == 0:  # minのみ-にする
    ans = sum_L-min(L)*2
    l = min(L)
    for r in L[1:-1]:
        process.append(str(l)+" "+str(r))
        l -= r
    process.append(str(L[-1])+" "+str(l))
elif N_neg == N:  # maxのみを+にする
    ans = -sum_L+max(L)*2
    l = L[-1]
    for r in reversed(L[:-1]):
        process.append(str(l)+" "+str(r))
        l -= r
else:  # negのやつを-にする
    ans = sum([abs(v) for v in L])
    l = L[0]
    for r in L[N_neg:-1]:
        process.append(str(l)+" "+str(r))
        l -= r
    process.append(str(L[-1])+" "+str(l))
    l = L[-1]-l
    for r in L[1:N_neg]:
        process.append(str(l)+" "+str(r))
        l -= r
print(ans)
print("\n".join(process))