Problem:


Score : 500 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 10^5

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

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

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

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

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

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

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

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

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0



Sample input:
3
1 -1 2


Sample output:
4
-1 1
2 -2

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=[]
C=[]
D=[]

for i in range(N):
  if A[i]<0:
    B.append(A[i])
  elif A[i]==0:
    C.append(A[i])
  else:
    D.append(A[i])

ans=[]
anss=0

if len(B)>0 and len(D)>0:
  for i in C:
    ans.append((B[0],0))
  for i in range(len(D)-1):
    ans.append((B[0],D[i]))
    B[0]-=D[i]
  for i in range(len(B)):
    ans.append((D[-1],B[i]))
    D[-1]-=B[i]
  anss=D[-1]

elif len(C)>0:
  for i in range(len(C)-1):
    ans.append((0,0))
  for i in B:
    ans.append((anss,i))
    anss-=i
  if(len(D)>0):
    for i in range(len(D)-1):
      ans.append((anss,D[i]))
      anss-=D[i]
    ans.append((D[-1],anss))
    anss=D[-1]-anss

else:
  E=sorted(B,reverse=True)+sorted(D)
  anss=E[0]
  for i in range(len(E)-2):
    ans.append((anss,E[i+1]))
    anss-=E[i+1]
  if anss<=0:
    ans.append((E[-1],anss))
    anss=E[-1]-anss
  else:
    ans.append((anss,E[-1]))
    anss-=E[-1]

print(anss)
for i in ans:
  print(*i)

Submission status: Accepted

Solution code:
import bisect

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

i0 = bisect.bisect_left(A,0)
if i0 >= N-1:
  print(-sum(A[:N-1])+A[N-1])
  a = A[N-1]
  for i in range(N-1):
    print(a,A[i])
    a = a-A[i]
elif i0 <= 1:
  print(-A[0]+sum(A[1:]))
  a = A[0]
  for i in range(1,N-1):
    print(a,A[i])
    a = a-A[i]
  print(A[N-1],a)
else:
  print(-sum(A[:i0])+sum(A[i0:]))
  a = A[i0-1]
  for i in range(i0,N-1):
    print(a,A[i])
    a = a-A[i]
  print(A[N-1],a)
  a = A[N-1]-a
  for i in range(i0-1):
    print(a,A[i])
    a = a-A[i]

Submission status: Accepted

Solution code:
import bisect

N = int(input())
A = list(map(int,input().split()))
A.sort()
if N == 2:
  print(A[1]-A[0])
  print(A[1],A[0])
  exit()
i0 = bisect.bisect_left(A,0)
if i0 >= N-1:
  print(-sum(A[:N-1])+A[N-1])
  a = A[N-1]
  for i in range(N-1):
    print(a,A[i])
    a = a-A[i]
elif i0 <= 1:
  print(-A[0]+sum(A[1:]))
  a = A[0]
  for i in range(1,N-1):
    print(a,A[i])
    a = a-A[i]
  print(A[N-1],a)
else:
  print(-sum(A[:i0])+sum(A[i0:]))
  a = A[i0-1]
  for i in range(i0,N-1):
    print(a,A[i])
    a = a-A[i]
  print(A[N-1],a)
  a = A[N-1]-a
  for i in range(i0-1):
    print(a,A[i])
    a = a-A[i]

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

N = I()
A = III()
A.sort(reverse=True)
plus = 0
for a in A:
    if a>0:
        plus += 1
if plus==N:
    plus -= 1

ans = []
val = A[plus]

if plus:
    for i in range(1,plus)[::-1]:
        ans.append((val,A[i]))
        val -= A[i]
    ans.append((A[0],val))
    val = A[0]-val

for i in range(plus+1,N):
    ans.append((val,A[i]))
    val -= A[i]

print(val)
for a in ans:
    print(*a, sep=' ')

Submission status: Accepted

Solution code:
N = int(input())
a = list(map(int, input().split()))
p = [t for t in a if t >= 0]
m = [t for t in a if t < 0]
p.sort(reverse = True)
m.sort()
l = []
if N == 2:
  print(max(a) - min(a))
  print(max(a), min(a))
  exit(0)
if len(p) == 0:
  u = m.pop()
  v = m.pop()
  l.append((u, v))
  p.append(u - v)
if len(m) == 0 and len(p) >= 2:
  u = p.pop()
  v = p.pop()
  l.append((u, v))
  m.append(u - v)
while len(p) >= 2:
  u = m.pop()
  v = p.pop()
  l.append((u, v))
  m.append(u - v)
while len(m):
  t = p[0]
  u = m.pop()
  l.append((t, u))
  p[0] = t - u
print(p[0])
for res in l:
  print(*res)

Submission status: Accepted

Solution code:
from bisect import bisect_left as bi
n = int(input())
a = [int(i) for i in input().split()]
a = sorted(a)
b,num = bi(a,0),a[0]
if b==n:
    q = n-1
    print(a[-1]-sum(a[:n-1]))
elif b:
    q = b
    print(sum(a[b:])-sum(a[:b]))
else:
    q = 1
    print(sum(a[1:])-a[0])
for i in range(q,n-1):
    print(num,a[i])
    num-=a[i]
print(a[-1],num)
num = a[-1]-num
for i in range(1,q):
    print(num,a[i])
    num-=a[i]

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = [int(i) for i in input().split()]
A.sort()
A = deque(A)
m = A.popleft()
ans = []
while len(A)>1:
  if A[-2]<=0:
    break
  x = A.pop()
  ans += [(m,x)]
  m = m-x
for i in range(len(A)-1):
  ans += [(A[-1],A[i])]
  A[-1] = A[-1]-A[i]

ans += [(A[-1],m)]
print(A[-1]-m)
for a in ans:
  print(*a)

Submission status: Accepted

Solution code:
import bisect

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

zp = bisect.bisect_left(A, 0)
ans = []

M = A[0]
for i in range(max(zp, 1), N-1):
    ans.append((M, A[i]))
    M -= A[i]

ans.append((A[N-1], M))
M = A[N-1]-M

for i in range(1, min(zp, N-1)):
    ans.append((M, A[i]))
    M -= A[i]


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

Submission status: Accepted

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

A.sort()
c = 0
for a in A:
    if a <= 0:
        c += 1

if c == N or c == N-1:
    ans = A[-1] - sum(A[:-1])
    print(ans)
    a, b = A[-1], A[0]
    for i in range(1, N):
        print(a, b)
        a, b = a-b, A[i]
elif c == 0 or c == 1:
    ans = sum(A[1:]) - A[0]
    print(ans)
    a, b = A[0], 0
    for i in range(1, N-1):
        a, b = a-b, A[i]
        print(a, b)
    a, b = A[-1], a-b
    print(a, b)
else:
    ans = sum(A[c:]) - sum(A[:c])
    print(ans)
    a, b = A[0], 0
    for i in range(N-c-1):
        a, b = a-b, A[c+i]
        print(a, b)
    a, b = A[-1], a-b
    print(a, b)
    for i in range(c-1):
        a, b = a-b, A[i+1]
        print(a, b)

Submission status: Accepted

Solution code:
N = int(input())

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

A.sort()

minimum, maximum = A[0], A[-1]
xy = []

for i in range(1,N-1):
    num = A[i]
    if num >= 0:
        xy.append((minimum, num))
        minimum -= num
    else:
        xy.append((maximum, num))
        maximum -= num

xy.append((maximum, minimum))
print(maximum-minimum)
for x, y in xy:
    print(x,y)

Submission status: Accepted

Solution code:
n,*l=map(int,open(0).read().split())
l.sort()
i=0
ans=[]
while l[i]<0:
  i+=1
  if i==n:
    break
minus=l[:i]
plus=l[i:]
if minus and plus:
  x=minus[0]
  for y in plus[:-1]:
    ans.append((x,y))
    x-=y
  minus[0]=x
  x=plus[-1]
  for y in minus:
    ans.append((x,y))
    x-=y
elif minus:
  x=minus[-1]
  for y in minus[:-1]:
    ans.append((x,y))
    x-=y
else:
  x=plus[0]
  for y in plus[1:-1]:
    ans.append((x,y))
    x-=y
  ans.append((plus[-1],x))
  x=plus[-1]-x
print(x)
for i,j in ans:
  print(i,j)

Submission status: Accepted

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

positive = 0
negative = 0

for a in A:
    if a > 0:
        positive += a
    else:
        negative += a

if positive == 0:  # 全部負
    # 一番大きい数から残りをすべて引く
    A.sort(reverse=True)
    now = A[0]
    ans = []
    for a in A[1:]:
        ans.append((now, a))
        now -= a
    print(now)
    for a in ans:
        print(*a)
elif negative == 0:  # 全部非負
    # 一番小さい数から引いて，最後に大きい数から引く
    A.sort()
    now = A[0]
    ans = []
    for a in A[1: N - 1]:
        ans.append((now, a))
        now -= a
    ans.append((A[-1], now))
    now = A[-1] - now
    print(now)
    for a in ans:
        print(*a)
else:
    A.sort()
    neg = A[0]
    pos = A[-1]
    ans = []
    for a in A[1: N - 1]:
        if a > 0:
            ans.append((neg, a))
            neg -= a
        else:
            ans.append((pos, a))
            pos -= a
    ans.append((pos, neg))
    print(pos - neg)
    for a in ans:
        print(*a)

Submission status: Accepted

Solution code:
N = int(input())
a = list(map(int, input().split()))
a.sort()
ans = []
if a[0] > 0:
    x = a[0]
    for i in range(1, N - 1):
        ans.append((x, a[i]))
        x -= a[i]
    ans.append((a[-1], x))
    x = a[-1] - x
elif a[-1] < 0:
    x = a[-1]
    for i in range(N - 2, -1, -1):
        ans.append((x, a[i]))
        x -= a[i]
else:
    x = a[0]
    for i in range(1, N - 1):
        if a[i] >= 0:
            ans.append((x, a[i]))
            x -= a[i]
    ans.append((a[-1], x))
    x = a[-1] - x
    for i in range(1, N - 1):
        if a[i] < 0:
            ans.append((x, a[i]))
            x -= a[i]

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

Submission status: Accepted

Solution code:
def main():

    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    
    if A[-1] < 0:
        maxv = -sum(A) + 2 * A[-1]
        cur = A[-1]
        ops = []
        for i in range(N-1):
            ops.append([cur, A[i]])
            cur -= A[i]
    elif A[0] >= 0:
        maxv = sum(A)-2*A[0]
        ops = []
        cur = A[0]
        for i in range(1, N-1):
            ops.append([cur, A[i]])
            cur -= A[i]
        ops.append([A[-1], cur])
    else:
        pos = []
        neg = []
        for a in A:
            if a < 0: neg.append(a)
            else: pos.append(a)
        maxv = sum(pos) - sum(neg)
        ops = []
        cur = neg[0]
        for i in range(len(pos)-1):
            ops.append([cur, pos[i]])
            cur -= pos[i]
        ops.append([pos[-1], cur])
        cur = pos[-1] - cur
        for i in range(1, len(neg)):
            ops.append([cur, neg[i]])
            cur -= neg[i]

    return maxv, ops

if __name__ == '__main__':
    output = main()
    print(output[0])
    for a, b in output[1]:
        print(" ".join(map(str, [a, b])))

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
import sys
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; cnt = 0; ansli = []; tmpli = []; candili = []; stillset = set()
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]#WideIntPoint
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def s_list(): return list(input())
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]#HeightString
def mi(n): return [wi() for _ in range(n)]#MatrixInt
def num_grid(n): return [[int(i) for i in sys.stdin.readline().split()[0]] for _ in range(n)]#NumberGrid
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]
def grid(n): return [s_list() for _ in range(n)]

n = i()
a = wi()

minus = 0
plus = 0

a.sort()
for i in range(n):
    if a[i] >= 0:
        plus += 1
    elif a[i] < 0:
        minus += 1

if plus == 0:
    minus -= 1
    plus += 1
elif plus == n:
    minus += 1
    plus -= 1


mli = []
pli = []
for i in range(1, n + 1):
    if i <= minus:
        ans += -a[i - 1]
        mli.append(a[i - 1])
    else:
        ans += a[i - 1]
        pli.append(a[i - 1])

print(ans)
for i in range(n - 1):
    if i == 0:
        if plus == 1:
            print(pli[0], mli[0])
            tmp = pli[0] - mli[0]
        else:
            print(mli[0], pli[0])
            tmp = mli[0] - pli[0]
    elif i < plus - 1:
        print(tmp, pli[i])
        tmp = tmp - pli[i]
    elif i == plus - 1:
        print(pli[i], tmp)
        tmp = pli[i] - tmp
    else:
        print(tmp, mli[i - plus + 1])
        tmp = tmp - mli[i - plus + 1]

Submission status: Accepted

Solution code:
N=int(input())
A=sorted(map(int,input().split()))
m,M=A[0],A[-1]
L=[]

for i in range(1,N-1):
    v=A[i]
    if v>=0:
        L.append((m,v))
        m-=v
    else:
        L.append((M,v))
        M-=v
L.append((M,m))
ans=M-m

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

Submission status: Accepted

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

A.sort()

for i,a in enumerate(A):
    if a>=0:break
B = A[:i]
C = A[i:]

ans = []
if not B:
    x = C[0]
    for a in C[1:-1]:
        ans.append((x,a))
        x -= a
    ans.append((C[-1],x))
    x = C[-1] - x
elif not C:
    x = B[-1]
    for a in B[:-1]:
        ans.append((x,a))
        x -= a
else:
    x = B[0]
    for a in C[1:]:
        ans.append((x,a))
        x -= a
    ans.append((C[0],x))
    x = C[0]-x
    for a in B[1:]:
        ans.append((x,a))
        x -= a

print(x)
for out in ans:
    print(*out)

Submission status: Accepted

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

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n = int(input())
a = list(map(int,input().split()))
a.sort()
ma = a[-1]
mi = a[0]
log = []
for i in a[1:-1]:
    if i >= 0:
        log.append([mi,i])
        mi -= i
    else:
        log.append([ma,i])
        ma -= i
log.append([ma,mi])
print(ma-mi)
for i in range(n-1):
    x,y = log[i]
    print(x,y)

Submission status: Accepted

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

min_value = inputs[0]
max_value = inputs[-1]
process = []
for i in range(1, N-1):
    value = inputs[i]
    if value >= 0:
        process.append([min_value, value])
        min_value -= value
    elif value < 0:
        process.append([max_value, value])
        max_value -= value
process.append([max_value, min_value])

print(max_value - min_value)
for item in process:
    print(item[0], item[1])

Submission status: Accepted

Solution code:
# diverta2019-2C - Successive Subtraction
def main():
    n = int(input())
    lst = sorted(map(int, input().rstrip().split()))
    s = lst[0]  # start
    l = lst[-1]  # last
    log = []
    for i in lst[1:-1]:
        if i > 0:
            log += [(s, i)]
            s -= i
        else:
            log += [(l, i)]
            l -= i
    log += [(l, s)]
    print(l - s)
    for i, j in log:
        print(i, j)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
*A, = map(int, input().split())
operations = []
pos = []; zero = []; neg = [];
for a in A:
    if a > 0: pos.append(a)
    elif a == 0: zero.append(a)
    else: neg.append(a)
pos.sort(); neg.sort()
if N == 2:
    a, b = max(A), min(A)
    ans = a - b
    operations.append((a, b))
else:
    if len(neg) == 0:
        pos = zero + pos
        operations.append((pos[0], pos[-1]))
        neg = [pos[0] - pos[-1]]
        pos = pos[1:-1]
    elif len(pos) == 0:
        neg = neg + zero
        operations.append((neg[-1], neg[0]))
        pos = [neg[-1] - neg[0]]
        neg = neg[1:-1]
    else:
        neg = neg + zero
    neg = neg[::-1]
    while len(pos) > 1 and len(neg) > 1:
        n, p = neg.pop(), pos.pop()
        operations.append((p, n))
        pos.append(p-n)
    if len(neg) == 1:
        while len(pos) > 1:
            n, p = neg.pop(), pos.pop()
            operations.append((n, p))
            neg.append(n-p)
    else:
        while len(neg) > 1:
            n, p = neg.pop(), pos.pop()
            operations.append((p, n))
            pos.append(p-n)
    operations.append((pos[0], neg[0]))
    ans = pos[0] - neg[0]
print(ans)
for x, y in operations:
    print(x, y)

Submission status: Accepted

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

AAA.sort()

m = AAA[0]
M = AAA[N-1]

procedures = []
for i in range(1, N-1):
    if AAA[i] > 0:
        procedures.append((m, AAA[i]))
        m -= AAA[i]
    else:
        procedures.append((M, AAA[i]))
        M -= AAA[i]
procedures.append((M, m))

print(M-m)
for x, y in procedures:
    print(x, y)

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:
import sys
sys.setrecursionlimit(10**7)
#n,m=map(int,input().split())
n=int(input())
a=[int(i) for i in input().split()]
a.sort()
if a[-1]<=0:
    x=a.pop()
    print(x-sum(a))
    for y in a:
        print(x,y)
        x=x-y
elif a[0]>=0:
    a=a[::-1]
    x=a.pop()
    print(-x+sum(a))
    while a:
        y=a.pop()
        if len(a)>0:
            print(x,y)
            x=x-y
        else:
            print(y,x)
            
else:
    for i in range(n):
        if a[i]>0:
            ap=a[i:]
            an=a[:i]
            break
    print(sum(ap)-sum(an))
    z=ap.pop()
    x=an.pop()
    for y in ap:
        print(x,y)
        x=x-y
    for y in an:
        print(z,y)
        z=z-y
    print(z,x)

Submission status: Accepted

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

AAA.sort()  # 昇順ソート

m = AAA[0]
M = AAA[N-1]
ANS = []

for i in range(1, N-1):
    if AAA[i] > 0:
        ANS.append((m, AAA[i]))
        m -= AAA[i]
        continue
    ANS.append((M, AAA[i]))
    M -= AAA[i]
ANS.append((M, m))

print(M-m)
for (x, y) in ANS:
    print(x, y)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort()
q = 0
for ai in a:
    if ai < 0:
        q += 1
    else:
        break
if q == 0:
    q = 1
elif q == n:
    q = n - 1
ans = []
x = a[0]
for ai in a[q:-1]:
    ans.append([x, ai])
    x -= ai

ans.append([a[-1], x])
y = a[-1] - x

for ai in a[1:q]:
    ans.append([y, ai])
    y -= ai

print(y)
for i in ans:
    print(*i)

Submission status: Accepted

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

# 正-負をなるべく多く達成するように操作する
P = sorted((a for a in A if a >= 0), reverse=True)
Q = sorted(a for a in A if a < 0)

x, y = [], []
if len(P) == 2 and not Q:
    Y, X = P.pop(), P.pop()
    x.append(X)
    y.append(Y)
    P.append(X - Y)
if len(P) >= 3 and not Q:
    X, Y = P.pop(), P.pop()
    x.append(X)
    y.append(Y)
    Q.append(X - Y)
if not P and len(Q) >= 2:
    X, Y = Q.pop(), Q.pop()
    x.append(X)
    y.append(Y)
    P.append(X - Y)
while len(P) >= 2 and Q:
    X, Y = Q.pop(), P.pop()
    x.append(X)
    y.append(Y)
    Q.append(X - Y)
while Q:
    X, Y = P.pop(), Q.pop()
    x.append(X)
    y.append(Y)
    P.append(X - Y)

ans = (
    '{}\n{}'.format(
        P[0],
        '\n'.join(
            '{} {}'.format(X, Y)
            for X, Y in zip(x, y)
        )
    )
)

# 出力
print(ans)

Submission status: Accepted

Solution code:

def solve():
    N = int(raw_input())
    A = [int(_) for _ in raw_input().split()]
    A.sort()
    ret = abs(A[N-1] - A[0])
    rever = [0] * (N - 1)
    for i in range(1, N-1):
        if A[i] >= 0:
            ret = ret + A[i]
            rever[i-1] = 1
        else:
            ret = ret - A[i]
    print ret
    def PrintAndCalcSave(a, b, rever):
        if rever == 0:
            print a, b
            return a - b
        else:
            print b, a
            return b - a

    cnt = 0
    if A[N-1] > A[0]:
        save = PrintAndCalcSave(A[N-1], A[0], rever[cnt])
    else:
        save = PrintAndCalcSave(A[0], A[N-1], rever[cnt])
    cnt += 1
    for i in range(1, N - 1):
        if A[i] >= 0:
            save = PrintAndCalcSave(A[i], save, rever[cnt])
        else:
            save = PrintAndCalcSave(save, A[i], rever[cnt])
        cnt += 1

if __name__ == '__main__':
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import deque

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

A.sort()
A_d = deque(A)

if (A_d[0] <= 0 and A_d[n-1] > 0) or (A_d[0] < 0 and A_d[n-1] >= 0):
    print(sum(list(map(abs, A_d))))
    while A_d[-2] >= 0:
        atama = A_d.popleft()
        ketu = A_d.pop()
        print(atama, ketu)
        new = atama - ketu
        A_d.appendleft(new)
    while len(A_d) != 1:
        atama = A_d.popleft()
        ketu = A_d.pop()
        print(ketu, atama)
        new = ketu - atama
        A_d.append(new)
elif A_d[0] > 0:
    atama = A_d.popleft()
    tugi = A_d.popleft()
    new = atama - tugi
    A_d.appendleft(new)
    print(sum(list(map(abs, A_d))))
    print(atama, tugi)
    while len(A_d) != 2:
        atama = A_d.popleft()
        ketu = A_d.pop()
        print(atama, ketu)
        new = atama - ketu
        A_d.appendleft(new)
    atama = A_d.popleft()
    ketu = A_d.pop()
    print(ketu, atama)
else:
    ketu = A_d.pop()
    tugi = A_d.pop()
    new = ketu - tugi
    A_d.append(new)
    print(sum(list(map(abs, A_d))))
    print(ketu, tugi)
    while len(A_d) != 1:
        atama = A_d.popleft()
        ketu = A_d.pop()
        print(ketu, atama)
        new = ketu - atama
        A_d.append(new)

Submission status: Accepted

Solution code:
import collections
N = int(input())
A = list(map(int, input().split()))
A.sort()
A2 = collections.deque(A)
#print(N, A)
x = [0] * (N-1)
y = [0] * (N-1)
for i in range(N -1):
    amin = A2.popleft()
    amax = A2.pop()
    mainasuflag = 0
    plusflag = 0
    if i != N - 2:
        if A2[0] > 0:
            mainasuflag = 1
        if A2[len(A2) - 1] < 0:
            plusflag = 1
        amin2 = abs(A2[0])
        amax2 = abs(A2[len(A2) -1])
        if i == N - 3:
            if A2[0] > 0:
                A2.appendleft(amin - amax)
                x[i] = amin
                y[i] = amax
            else:
                A2.append(amax - amin)
                x[i] = amax
                y[i] = amin
        else:
            if mainasuflag == 1:
                A2.appendleft(amin - amax)
                x[i] = amin
                y[i] = amax
            elif plusflag == 1:
                A2.append(amax - amin)
                x[i] = amax
                y[i] = amin
            else:
                if amax2 >= amin2:
                    A2.appendleft(amin - amax)
                    x[i] = amin
                    y[i] = amax
                else:
                    A2.append(amax - amin)
                    x[i] = amax
                    y[i] = amin

    else:
        A2.append(amax - amin)
        x[i] = amax
        y[i] = amin

    #print("A", A2, mainasuflag, plusflag)

print(A2[0])
#print(x, y)
for i in range(N - 1):
    print(x[i], y[i])

Submission status: Accepted

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

N = int(input())
a = list(map(int,input().split()))
a.sort()
s = a[0]
l = a[-1]
log = []
for i in a[1:-1]:
    if i > 0:
        log += [(s, i)]
        s -= i
    else:
        log += [(l, i)]
        l -= i
log += [(l, s)]
print(l - s)
for i, j in log:
    print(i, j)

Submission status: Accepted

Solution code:
# div2019-2C - Successive Subtraction
def main():
    n = int(input())
    lst = sorted(list(map(int, input().rstrip().split())))
    s = lst[0]
    l = lst[-1]
    log = []
    for i in lst[1:-1]:
        if i > 0:
            log += [(s, i)]
            s -= i
        else:
            log += [(l, i)]
            l -= i
    log += [(l, s)]
    print(l - s)
    for i, j in log:
        print(i, j)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect

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

neg = [A[0]]
pos = [A[-1]]
if N >= 3:
    i = bisect.bisect_left(A, 0, lo=1, hi=N - 1)
    neg += A[1:i]
    pos += A[i:N - 1]

M = neg.pop()
Op = []
for i in range(len(pos) - 1):
    p = pos.pop()
    Op.append((M, p))
    M -= p
p = pos.pop()
Op.append((p, M))
M = p - M
for i in range(len(neg)):
    n = neg.pop()
    Op.append((M, n))
    M -= n

print(M)
for O in Op:
    print(O[0], O[1])

Submission status: Accepted

Solution code:
def c(n,a):
    a.sort()
    max = a.pop()
    min = a.pop(0)
    opr = []
    for i in a:
        if i >= 0:
            opr.append('{} {}'.format(min, i))
            min-=i
        else:
            opr.append('{} {}'.format(max, i))
            max-=i
    opr.append('{} {}'.format(max, min))
    return str(max - min) + '\n' + '\n'.join(opr)

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

Submission status: Accepted

Solution code:
import bisect
n = int(input())
a = [int(i) for i in input().split()]
a.sort()
point = bisect.bisect_right(a, 0)
a_minus = a[:point]
a_plus = a[point:]
len_plus = len(a_plus)
if (len(a_minus) > 0) & (len(a_plus) > 0):
    ans = sum(a_plus) - sum(a_minus)
    print(ans)
    for i in range(len(a_plus)):
        if len_plus == 1:
            x = a_plus.pop(0)
            y = a_minus.pop(0)
            print(str(x) + " " + str(y))
        elif (i == 0):
            x = a_minus.pop(0)
            y = a_plus.pop(0)
            print(str(x) + " " + str(y))
        elif i == len_plus - 1:
            y = x - y
            x = a_plus.pop(0)
            print(str(x) + " " + str(y))
        else:
            x = x - y
            y = a_plus.pop(0)
            print(str(x) + " " + str(y))
    for j in range(len(a_minus)):
        x = x - y
        y = a_minus.pop(0)
        print(str(x) + ' ' + str(y))
elif len(a_plus) > 0:
    ans = sum(a_plus) - ((a[0]) * 2)
    print(ans)
    for i in range(len(a_plus) - 1):
        if i == 0:
            x = a_plus.pop(0)
            y = a_plus.pop(0)
            print(str(x) + " " + str(y))
        elif i == len_plus - 2:
            y = x - y
            x = a_plus.pop(0)
            print(str(x) + " " + str(y))
        else:
            x = x - y
            y = a_plus.pop(0)
            print(str(x) + " " + str(y))
elif len(a_minus) > 0:
    ans = (a_minus[-1] * 2) - sum(a_minus)
    print(ans)
    for i in range(len(a_minus) - 1):
        if i == 0:
            x = a_minus[-1]
            y = a_minus.pop(0)
            print(str(x) + " " + str(y))
        elif i == len_plus - 2:
            x = x - y
            y = a_minus.pop(0)
            print(str(x) + " " + str(y))
        else:
            x = x - y
            y = a_minus.pop(0)
            print(str(x) + " " + str(y))

Submission status: Accepted

Solution code:
n=int(input())
a=sorted(list(map(int,input().split())))
max=a[-1]
min=a[0]
if n==2:
    print(max-min)
    print(max,min)
    exit()
ans=0
if a[-1]<0:
    ans+=-sum(a)+max*2
elif a[0]>0:
    ans+=sum(a)-min*2
else:
    for x in a:
        ans+=abs(x)
print(ans)
X=max
Y=min
for i in range(1,n-1):
    if a[i]>=0:
        x=Y
        y=a[i]
        print(x,y)
        Y=x-y    
    else:
        x=X
        y=a[i]
        print(x,y)
        X=x-y
print(X,Y)

Submission status: Accepted

Solution code:
import sys
import collections as col
import bisect
import numpy as np


def main():
    n = int(input())
    aarray = [int(e) for e in input().split()]
    aarray.sort()
    record = []
    endpoint = max(1, bisect.bisect(aarray, 0))
    aqueue = col.deque(aarray)
    while len(aqueue) > endpoint + 1:
        amax = aqueue.pop()
        amin = aqueue.popleft()
        record.append((amin, amax))
        aqueue.appendleft(amin - amax)
    amax = aqueue.pop()
    while len(aqueue) > 0:
        amin = aqueue.popleft()
        record.append((amax, amin))
        amax -= amin
    print(amax)
    for r in record:
        print(r[0], r[1])


main()

Submission status: Accepted

Solution code:
from heapq import heappop,heappush
n = int(input())
A = sorted(list(map(int,input().split())))
P = []
M = []
if n == 2:
    print(A[1]-A[0])
    print(A[1],A[0])
    exit()
def move():
    while len(P)!= 1:
        mm = heappop(M)
        pp = heappop(P)
        print(mm,pp)
        heappush(M,mm-pp)
    while len(M) != 0:
        mm = heappop(M)
        pp = heappop(P)
        print(pp,mm)
        heappush(P,pp-mm)
for a in A:
    if a>=0:
        P.append(a)
    else:
        M.append(a)

if A[-1]>=0 and A[0]<0:
    print(sum(abs(a) for a in A))
elif A[0]>=0:
    print(sum(A)-min(A)*2)
    mm = heappop(P)
    pp = heappop(P)
    print(mm,pp)
    heappush(M,mm-pp)
else:
    print(sum(abs(a) for a in A)+max(A)*2)
    mm = M[-1]
    pp = M[-2]
    print(mm,pp)
    M = M[:-2]
    heappush(P,mm-pp)
move()