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 = sorted(list(map(int,input().split())))
if a[n-1] < 0:
    ans = 2*a[n-1]-sum(a)
    print(ans)
    p,q =a[n-1],a[0]
    for i in range(n-1):
        print(p,q)
        p = p-q
        q = a[i+1]
elif a[0] >= 0:
    ans = sum(a)-2*a[0]
    print(ans)
    p,q = a[0],a[1]
    for i in range(n-2):
        print(p,q)
        p = p-q
        q = a[i+2]
    print(q,p)

else:
    num = 0
    ans = 0
    for i in range(n):
        if a[i] < 0:
            ans -=a[i]
        else:
            if a[i-1] < 0 and a[i] >= 0:
                num = i
            ans += a[i]
    print(ans)
    p = a[0]
    for i in range(num,n-1):
        print(p,a[i])
        p -= a[i]
    q = a[n-1]
    print(q,p)
    q -= p
    for i in range(1,num):
        print(q,a[i])
        q -= a[i]

Submission status: Accepted

Solution code:
N, *A = map(int, open(0).read().split())

x = sorted([v for v in A if v >= 0])
y = sorted([v for v in A if v < 0], reverse=True)

ans = []
if len(y) == 0:
    cnt = x[0]
    for v in x[1:-1]:
        ans.append((cnt, v))
        cnt -= v
    ans.append((x[-1], cnt))
    print(x[-1] - cnt)
elif len(x) == 0:
    cnt = y[0]
    for v in y[1:]:
        ans.append((cnt, v))
        cnt -= v
    print(cnt)
else:
    for v in x[:-1]:
        ans.append((y[0], v))
        y[0] -= v
        
    cnt = x[-1]
    for v in y:
        ans.append((cnt, v))
        cnt -= v
    print(cnt)
    
for v in ans:
    print(*v)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
a.sort()
a_left, a_right = a[0], a.pop()
ans_list = []
for i in range(1, n - 1):
    ans_list.append([[a_right, a_left][a[i] >= 0], a[i]])
    a_right, a_left = a_right - [a[i], 0][a[i] >= 0], a_left - [0, a[i]][a[i] >= 0]
ans_list.append([a_right, a_left])
print(a_right - a_left)
[print(*ans_list[i]) for i in range(n-1)]

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int,input().split()))
l.sort()
if l[0]>=0 :
  print(sum(l)-2*l[0])
  for i in range(1,n-1):
    print(l[0],l[i])
    l[0]-=l[i]
  print(l[-1],l[0])
elif l[-1]<0:
  print(abs(sum(l)-2*l[-1]))
  for i in range(n-1):
    print(l[-1],l[i])
    l[-1]-=l[i]
else:
  cnt=0
  i=0
  while l[i]<0:
    cnt+=1
    if l[i+1]>=0:
      break
    i+=1
  ans=0
  for j in range(n):
    ans+=abs(l[j])
  print(ans)
  for j in range(n-2-i):
    print(l[0],l[i+j+1])
    l[0]-=l[i+j+1]
  for j in range(i+1):
    print(l[-1],l[j])
    l[-1]-=l[j]

Submission status: Accepted

Solution code:
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
import bisect
import copy
import fractions
import itertools
import math
import queue
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers): return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers): return reduce(LCM, numbers)
def LCM(m, n): return (m * n // fractions.gcd(m, n))


n = II()
a = sorted(LI(), reverse=True)
ans = []
s = 0
if all([i < 0 for i in a]):
    tmp = a[0]
    for i in range(1, n):
        ans.append((tmp, a[i]))
        tmp -= a[i]
    print(tmp)
    for i in ans:
        print(i[0], i[1])
else:
    tmp = a[-1]
    for i in range(1, n - 1):
        if a[i] < 0:
            break
        ans.append((tmp, a[i]))
        tmp -= a[i]

    ans.append((max(a), tmp))
    tmp = max(a) - tmp

    for i in range(1, n - 1):
        if a[i] >= 0:
            continue
        ans.append((tmp, a[i]))
        tmp -= a[i]
    print(tmp)
    for i in ans:
        print(i[0], i[1])

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
ans = 0
a.sort()
a_left, a_right = a[0], a.pop()
minus, plus = [], []
for i in range(1, n - 1):
    if a[i] < 0:
        minus.append(a[i])
    else:
        plus.append(a[i])

ans_list = []
for i in range(len(minus)):
    ans_list.append([a_right ,minus[i]])
    a_right -= minus[i]
for i in range(len(plus)):
    ans_list.append([a_left ,plus[i]])
    a_left -= plus[i]
ans_list.append([a_right, a_left])

print(a_right - a_left)
[print(*ans_list[i]) for i in range(n-1)]

Submission status: Accepted

Solution code:
from collections import deque
plusQ = deque([]) 
minsQ = deque([])
 
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
 
for itr, val in enumerate(A):
  if itr == 0:
    plusQ.append(val)
  elif itr != len(A) - 1 and val > 0:
    plusQ.append(val)
  else:
    minsQ.append(val)
    
p1 = plusQ.popleft()
 
ans = deque([])
while len(minsQ) > 0:
  if len(plusQ) > 0:
    p, m = plusQ.popleft(), minsQ.popleft()
    ans.append([m, p])
    minsQ.append(m - p)    
  else:
    m = minsQ.popleft()
    ans.append([p1, m])
    p1 = p1 - m

print(p1)
while len(ans) > 0:
  hoge = ans.popleft()
  print(hoge[0],hoge[1])

Submission status: Accepted

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

print(a[-1] - a[0] + sum(map(abs, a[1:-1])))

pos = [a[-1]]
neg = [a[0]]
for x in a[1:-1]:
    if x > 0:
        pos.append(x)
    else:
        neg.append(x)
now = neg[0]
for p in pos[1:]:
    print(now, p)
    now -= p
print(pos[0], now)
now = pos[0] - now
for n in neg[1:]:
    print(now, n)
    now -= n

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
a = deque(sorted(map(int, input().split())))


max_a = a.pop()
min_a = a.popleft()

ans_s = ""
while True:
    if len(a) <= 0:
        ans_s += "{} {}\n".format(max_a, min_a)
        ans = max_a - min_a
        break

    if max_a <= 0:
        ans_s += "{} {}\n".format(max_a, min_a)
        max_a -= min_a

        min_a = a.popleft()
    elif min_a >= 0:
        ans_s += "{} {}\n".format(min_a, max_a)
        min_a -= max_a

        max_a = a.pop()
    else:
        w = a.pop()
        if w < 0:
            ans_s += "{} {}\n".format(max_a, w)
            max_a -= w
        else:
            ans_s += "{} {}\n".format(min_a, w)
            min_a -= w

print(ans)
print(ans_s, end="")

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split()]
plus = [x for x in A if x > 0]
minus = [x for x in A if x <= 0]
plus.sort()
minus.sort()
minA = minus.pop() if minus else plus.pop(0)
M = sum(plus) - sum(minus)
M += -minA if plus else minA
print(M)
xy = minA
for i in range(N - 1):
  if len(plus) > 1:
    y = plus.pop()
    print('{} {}'.format(xy, y))
    xy -= y
  elif len(plus) == 1:
    x = plus.pop()
    print('{} {}'.format(x, xy))
    xy = x - xy
  else:
    y = minus.pop()
    print('{} {}'.format(xy, y))
    xy -= y

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
a.sort()

out = ""

minus = [a[0]]
plus = [a[-1]]

for v in a[1:-1]:
    if v < 0:
        minus.append(v)
    else:
        plus.append(v)

# (plus[0] - (minus[0] - plus[n])) - minus[n]
base_minus = minus.pop(0)
base_plus = plus.pop(0)
for i in range(len(plus)):
    x = base_minus
    y = plus[i]
    out += "{} {}\n".format(x, y)
    base_minus = x - y

out += "{} {}\n".format(base_plus, base_minus)
base_plus -= base_minus

for i in range(len(minus)):
    x = base_plus
    y = minus[i]
    out += "{} {}\n".format(x, y)
    base_plus = x - y
print(base_plus)
print(out)

Submission status: Accepted

Solution code:
import bisect

def main():
	n = int(input())
	a = list(map(int,input().split()))
	a.sort()
	idx = bisect.bisect_left(a,0)
	if idx == 0:
		idx = 1
	elif idx == n:
		idx = -1
	cur_min = a[0]
	cur_max = a[-1]
	res = []
	for n in a[1:idx]:
		res.append('{} {}'.format(cur_max,n))
		cur_max -= n
	for n in a[idx:-1]:
		res.append('{} {}'.format(cur_min,n))
		cur_min -= n
	res.append('{} {}'.format(cur_max,cur_min))
	print(cur_max-cur_min)
	for r in res:
		print(r)

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
N = int(input())
a = list(map(int, input().split()))
a.sort()
t = 0
for m in range(N):
    if a[m] < 0:
        t += 1
if N > 2:
    if t == 0:
        c = a[0]
        for i in range(N - 2):
            c = c - a[N - 1 - i]
        d = a[1] - c
        print(d)
        e = a[0]
        f = a[N - 1]
        for j in range(N - 2):
            print(e, end = ' ')
            print(f)
            e = e - f
            f = a[N - 2 - j]
        print(a[1], end = ' ')
        print(e)
    elif t > 0 and t < N - 1:
        c = 0
        for i in range(t):
            c += a[i] 
        for j in range(N - t -1):
            c = c - a[t + 1 + j]
        d = a[t] - c
        print(d)
        e = a[0]
        f = a[N - 1]
        for k in range(N - t - 1):
            print(e, end = ' ')
            print(f)
            e = e - f
            f = a[N - 2 - k]
        a[0] = e
        g = a[t]
        for l in range(t):
            print(g, end = ' ')
            print(a[l])
            g = g - a[l]
    elif t == N - 1 or t == N:
        c = a[N - 1]
        for i in range(N - 1):
            c = c - a[i]
        print(c)
        d = a[N - 1]
        for j in range(N - 1):
            print(d, end = ' ')
            print(a[j])
            d -= a[j]
else:
    print(a[1] - a[0])
    print(a[1], end = ' ')
    print(a[0])

Submission status: Accepted

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

p = A[-1]
n = A[0]

ans_list = []

for a in A[1:-1]:
    if a >= 0:
        ans_list.append((n, a))
        n -= a
    else:
        ans_list.append((p, a))
        p -= a

M = p - n
ans_list.append((p, n))

print(M)
for x, y in ans_list:
    print(x, y)

Submission status: Accepted

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

ans_list = []
p = []
n = []

# 最大にプラス、最小にマイナスを割り当てる
p.append(A[-1])
n.append(A[0])

# 正ならプラスを負ならマイナスを割り当てる
for a in A[1:-1]:
    if a >= 0:
        p.append(a)
    elif a < 0:
        n.append(a)

# プラスが１つになるまで消す
res = n[0]
for ep in p[1:]:
    ans_list.append((res, ep))
    res -= ep
n[0] = res
p = [p[0]]

# マイナスがなくなるまで消す
res = p[0]
for en in n:
    ans_list.append((res, en))
    res -= en

# 残ったものが最大値
M = res
print(M)
for x, y in ans_list:
    print(x, y)

Submission status: Accepted

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

A = sorted(A)

count_m = 0
count_z = 0
count_p = 0
sum_abs = 0

for i in range(N):
    if A[i] < 0:
        count_m += 1
        sum_abs -= A[i]
    elif A[i] == 0:
        count_z += 1
    else:
        count_p += 1
        sum_abs += A[i]

if count_m + count_z == 0:
    print(sum_abs-2*min(A))
    tmp = A[0]
    for i in range(N-2):
        print(tmp, A[i+1])
        tmp -= A[i+1]
    print(A[-1], tmp)

elif count_p + count_z == 0:
    print(sum_abs+2*max(A))
    tmp = A[-1]
    for i in range(N-1):
        print(tmp, A[i])
        tmp -= A[i]

elif count_p + count_m == 0:
    print(0)
    for i in range(N-1):
        print(0, 0)

else:
    print(sum_abs)
    cmz = count_m + count_z
    tmp = A[-1]
    for i in range(cmz - 1):
        print(tmp, A[i])
        tmp -= A[i]
    tmp_2 = A[cmz-1]
    if count_p != 0:
        for i in range(count_p-1):
            print(tmp_2, A[i+cmz])
            tmp_2 -= A[i+cmz]
        print(tmp, tmp_2)

Submission status: Accepted

Solution code:
from collections import deque

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

ans_list = []
p = deque()
n = deque()

# 最大にプラス、最小にマイナスを割り当てる
p.append(A[-1])
n.append(A[0])

# 正ならプラスを負ならマイナスを割り当てる
for a in A[1:-1]:
    if a >= 0:
        p.append(a)
    elif a < 0:
        n.append(a)

# プラスが１つになるまで消す
while len(p) != 1:
    x = n.pop()
    y = p.pop()
    n.append(x-y)
    ans_list.append((x, y))

# マイナスがなくなるまで消す
while len(n) != 0:
    x = p.pop()
    y = n.pop()
    p.append(x-y)
    ans_list.append((x,y))

# 残ったものが最大値
M = p[0]
print(M)
for x, y in ans_list:
    print(x, y)

Submission status: Accepted

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

ans_list = []
p = []
n = []

# 最大にプラス、最小にマイナスを割り当てる
p.append(A[-1])
n.append(A[0])

# 正ならプラスを負ならマイナスを割り当てる
for a in A[1:-1]:
    if a >= 0:
        p.append(a)
    elif a < 0:
        n.append(a)

# プラスが１つになるまで消す
while len(p) != 1:
    x = n.pop()
    y = p.pop()
    n.append(x-y)
    ans_list.append((x, y))

# マイナスがなくなるまで消す
while len(n) != 0:
    x = p.pop()
    y = n.pop()
    p.append(x-y)
    ans_list.append((x,y))

# 残ったものが最大値
M = p[0]
print(M)
for x, y in ans_list:
    print(x, y)

Submission status: Accepted

Solution code:
def c_successive_subtraction(N, A):
    A.sort()
    maximum = A.pop()
    minimum = A.pop(0)

    # Aの要素のうち、最大のものと最小のものを分けて置いておく。
    # それら以外の要素 a_k について、
    # a_k が非負なら、最小のものから a_k を引くことで負の方向に大きくできる。
    # a_k が負なら、最大のものから a_k を引くことで正の方向に大きくできる。
    # 最後に 最大のもの - 最小のもの とすると、最後に残る整数を最大にできる。
    operation = []
    for a in A:
        if a >= 0:
            operation.append('{} {}'.format(minimum, a))
            minimum -= a
        else:
            operation.append('{} {}'.format(maximum, a))
            maximum -= a
    operation.append('{} {}'.format(maximum, minimum))
    return str(maximum - minimum) + '\n' + '\n'.join(operation)

N = int(input())
A = [int(i) for i in input().split()]
print(c_successive_subtraction(N, A))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import bisect
n = int(input())
a = sorted(map(int, input().split()))
if n == 2:
    print(a[1] - a[0])
    print(a[1], a[0])
    exit()

p = bisect.bisect_left(a, 0)
p = min(max(1, p), n - 1)
print(sum(a[p:]) - sum(a[:p]))
b = a[p - 1]
for i in range(p, n - 1):
    print(b, a[i])
    b -= a[i]
c = a[n - 1]
for i in range(p - 1):
    print(c, a[i])
    c -= a[i]
print(c, b)

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    minus = []
    plus = []
    M = I()
    A = LI()
    zero = []
    ans = []
    for a in A:
        if a < 0:
            minus.append(a)
        elif a > 0:
            plus.append(a)
        else:
            zero.append(0)
    minus.sort()
    plus.sort(reverse = True)
    if not minus:
        #print(minus,plus,zero)
        if zero and plus:
            a = zero.pop()
            b = plus.pop()
            minus.append(a-b)
            ans.append("{} {}".format(a, b))
        elif len(plus) >= 2:
            a = plus.pop()
            b = plus.pop()
            minus.append(a-b)
            ans.append("{} {}".format(a, b))
        
    if not plus:
        if zero and minus:
            a = zero.pop()
            b = minus.pop()
            plus.append(a-b)
            ans.append("{} {}".format(a, b))
        elif len(minus):
            a = minus.pop()
            b = minus.pop()
            plus.append(a-b)
            ans.append("{} {}".format(a, b))
        


    while minus and plus:
        if len(minus) == len(plus) == 1:
            a = plus.pop()
            b = minus.pop()
            ans.append("{} {}".format(a,b))
            plus.append(a - b)
            break
        a = minus.pop()
        b = plus.pop()
        if len(minus) > len(plus):
            ans.append("{} {}".format(b,a))
            plus.append(b-a)
        else:
            ans.append("{} {}".format(a,b))
            minus.append(a - b)

    while zero:
        if minus:
            a = zero.pop()
            b = minus.pop()
            #print(a, b)
        elif plus:
            a = plus.pop()
            b = zero.pop()
            #print(a, b)
        elif len(zero) >= 2:
            a = zero.pop()
            b = zero.pop()
            #print(a,b)
        else:
            break
        plus.append(a - b)
        ans.append("{} {}".format(a,b))

    if zero:
        print(*zero)
    elif minus:
        print(*minus)
    else:
        print(*plus)
    print(*ans,sep="\n")

if __name__ == '__main__':
    main()

Submission status: Accepted

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

result = []
# all +
if a[0] > 0:
    if len(a) == 2:
        print(a[1]-a[0])
        print(a[1], a[0])
        exit()
    result.append((a[0], a[1]))
    t = a[0]-a[1]
    a.pop(0)
    a[0] = t
# all -
elif a[-1] < 0:
    if len(a) == 2:
        print(a[0]-a[1])
        print(a[0], a[1])
        exit()
    result.append((a[-1], a[-2]))
    t = a[-1]-a[-2]
    a.pop(-1)
    a[-1] = t

# print(a)
b = []
for i in range(len(a)-1):
    if a[i] > 0:
        result.append((b[0], a[i]))
        t = b[0]-a[i]
        b[0] = t
    else:
        b.append(a[i])
b.append(a[-1])
# print(b)
while len(b) != 1:
    result.append((b[-1], b[0]))
    b.append(b[-1]-b[0])
    b.pop(0)
    b.pop(-2)
# print(b)

print(b[0])
for r in result:
    print(r[0],r[1])

Submission status: Accepted

Solution code:
import bisect
N = int(input())
A = sorted(list(map(int, input().split())))
if N == 2:
    x, y = A[1], A[0]
    print(x-y)
    print(x, y)
    exit()
idx = bisect.bisect_left(A, 0)
if idx:
    if idx < N:
        Q = A[:idx]
        P = A[idx:]
    else:
        Q = A[:-1]
        P = [A[-1]]
else:
    Q = [A[0]]
    P = A[1:]


XY = []
LP = len(P)
for i in range(LP-1):
    XY.append((Q[0], P[i]))
    Q[0] -= P[i]
LQ = len(Q)
for i in range(LQ):
    XY.append((P[-1], Q[i]))
    P[-1] = P[-1] - Q[i]
ans = P[-1]
print(ans)
for x, y in XY:
    print(x, y)

Submission status: Accepted

Solution code:
N=int(input())
A=[]
r=[]
for i in input().split():
  A.append(int(i))
#入力した配列をソート
A.sort()

#Queue操作
t=A.pop(-1) #最大値をとりだす
#print('t=',t)
b=A.pop(0)  #最小値をとりだす
#print('b=',b)

#残りの配列において
for i in A:
  #print(i)
  #非負の場合
  if i>=0:
    r.append([b,i]) #最小値と現在の値のペア
    b=b-i  #bを更新
  #負の場合
  else:
    r.append([t,i]) #最大値と現在の値のペア
    t=t-i #tを更新
print(t-b)
r.append([t,b])
for i in r:
  #print(i)
  print(i[0],i[1])

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
plus=[a[i] for i in range(n) if a[i]>=0]
l_plus=len(plus)
minus=[a[i] for i in range(n) if a[i]<0]
l_minus=len(minus)
x_cal=[]
y_cal=[]
if n==2:
  a.sort()
  print(a[1]-a[0])
  print(a[0],a[1])
else:
  if plus!=[] and minus!=[]:
    if l_plus>1:
      x_cal.append(minus[0])
    for j in range(1,l_plus-1):
      x_cal.append(x_cal[-1]-plus[j])
    for k in range(1,l_plus):
      y_cal.append(plus[k])
    if l_plus>1:
      y_last=x_cal[-1]-y_cal[-1]
    else:
      y_last=minus[0]
    x_cal.append(plus[0])
    for j in range(1,l_minus):
      x_cal.append(x_cal[-1]-minus[j])
    for k in range(1,l_minus):
      y_cal.append(minus[k])
    y_cal.append(y_last)
    print(x_cal[-1]-y_cal[-1])
    for ii in range(n-1):
      print(x_cal[ii],y_cal[ii])
  elif minus==[]:
    a.sort()
    print(sum(a)-2*a[0])
    x_cal.append(a[0])
    for ij in range(1,n-2):
      x_cal.append(x_cal[-1]-a[ij])
    for jj in range(0,n-2):
      y_cal.append(a[jj+1])
    y_cal.append(x_cal[-1]-y_cal[-1])
    x_cal.append(a[-1])
    for ii in range(n-1):
      print(x_cal[ii],y_cal[ii])
  else:
    a.sort()
    print(a[-1]*2-sum(a))
    x_cal.append(a[-1])
    for ij in range(1,n-2):
      x_cal.append(x_cal[-1]-a[ij])
    for jj in range(0,n-2):
      y_cal.append(a[jj+1])
    x_cal.append(x_cal[-1]-y_cal[-1])
    y_cal.append(a[0])
    for ii in range(n-1):
      print(x_cal[ii],y_cal[ii])

Submission status: Accepted

Solution code:
import sys

def bigsmall(x,y):
    return (x,y) if x>y else (y,x)

def main():
    n = int(input())
    a = list(map(int, input().split()))
    a.sort()

    if len(a) == 2:
        b,s = bigsmall(a[0],a[1])
        print(b-s)
        print(b,s)
        sys.exit()

    ops = []
    curr = 0
    b,s = bigsmall(a[0],a[-1])
    if a[1] <= 0:
        ops.append((b,s))
        curr = b - s
    else:
        ops.append((s,b))
        curr = s - b

    del a[-1]
    a.append(-1) # to set answer > 0

    for i in range(1, len(a)-1):
        b,s = bigsmall(curr,a[i])

        if a[i+1] <= 0:
            ops.append((b,s))
            curr = b - s
        else:
            ops.append((s,b))
            curr = s - b

    print(curr)
    for x,y in ops:
        print(x,y)

if __name__=='__main__':
    main()

Submission status: Accepted

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

from collections import deque
import itertools as ite
import sys
import math

sys.setrecursionlimit(1000000)

INF = 10 ** 18
MOD = 10 ** 9 + 7

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

pos1 = pos2 = 0
flag1 = flag2 = False
for i in range(N):
	if A[i] > 0:
		flag1 = True
		pos1 = i
	elif A[i] < 0:
		flag2 = True
		pos2 = i

if flag1 and flag2:
	print sum(abs(num) for num in A)
	n1 = A[pos1]
	n2 = A[pos2]
	for i in range(N):
		if i == pos1 or i == pos2:
			continue
		if A[i] > 0:
			print n2, A[i]
			n2 -= A[i]
		else:
			print n1, A[i]
			n1 -= A[i]
	print n1, n2
elif flag1:
	pos = 0
	for i in range(N):
		if A[pos] > A[i]:
			pos = i
	S = 0
	if pos == 0:
		S = 1
	n1 = A[pos]
	print sum(A) - n1 * 2
	for i in range(N):
		if i == pos or i == S:
			continue
		print n1, A[i]
		n1 -= A[i]
	print A[S], n1
else:
	pos = 0
	for i in range(N):
		if A[pos] < A[i]:
			pos = i
	n1 = A[pos]
	print -sum(A) + n1 * 2
	for i in range(N):
		if i == pos:
			continue
		print n1, A[i]
		n1 -= A[i]

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

def main():
    N = II()
    A = LI()

    A.sort()
    from bisect import bisect
    slice_ = bisect(A, 0)
    from collections import deque
    minus = deque(A[:slice_])
    plus = deque(A[slice_:])
    # print(minus, plus)

    if minus and plus:
        first_plus = plus.popleft()
        first_minus = minus.popleft()
    elif minus and not plus:
        first_plus = minus.pop()  # must be the max of minuses
        first_minus = minus.popleft()
    elif plus and not minus:
        first_minus = plus.popleft()  # must be the min of pluses
        first_plus = plus.popleft()

    # first_plus - (first_minus - plus - plus - ...) - minus - minus - ...
    tmp = first_minus
    ans_li = []
    while len(plus) > 0:
        p = plus.popleft()
        ans_li.append((tmp, p))
        tmp = tmp - p
    ans_li.append((first_plus, tmp))
    tmp = first_plus - tmp
    while len(minus) > 0:
        m = minus.popleft()
        ans_li.append((tmp, m))
        tmp = tmp - m
    print(tmp)
    for i in ans_li: print('{} {}'.format(*i))


main()

Submission status: Accepted

Solution code:
l = input().split()
n = int(l[0])

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

# print(N, A)

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

def print_ans(ans, pairs):
    print(ans)
    for p in pairs:
        print(p[0], p[1])

def solve_p(A):
    ans = A[0]
    pairs = []
    for i in range(1, n - 1):
        pairs.append((ans, A[i]))
        ans -= A[i]

    pairs.append((A[n - 1], ans))
    ans = A[n - 1] - ans
    print_ans(ans, pairs)

def solve_n(A):
    A.sort(key=lambda x: -x)
    ans = A[0]
    pairs = []
    for i in range(1, n - 1):
        pairs.append((ans, A[i]))
        ans -= A[i]

    pairs.append((ans, A[n - 1]))
    ans -= A[-1]
    print_ans(ans, pairs)

# #P == 1
def solve1(P, N):
    ans = P[0]
    pairs = []
    for n in N:
        pairs.append((ans, n))
        ans -= n
    print_ans(ans, pairs)

# #N == 1 #P > 1
def solve2(P, N):
    ans = N[0]
    pairs = []
    for i in range(len(P) - 1):
        pairs.append((ans, P[i]))
        ans -= P[i]
    pairs.append((P[-1], ans))
    ans = P[-1] - ans
    print_ans(ans, pairs)

# #P > #N
def solve3(P, N):
    num_p = len(P)
    num_n = len(N)
    ans = P[0]
    pairs = []
    for i in range(num_n - 1):
        pairs.append((ans, N[i]))
        ans -= N[i]
    pairs.append((N[-1], ans))
    ans = N[-1] - ans
    for i in range(1, num_p - 1):
        pairs.append((ans, P[i]))
        ans -= P[i]
    pairs.append((P[-1], ans))
    ans = P[-1] - ans
    print_ans(ans, pairs)

num_p = len(P)
num_n = len(N)
if num_p == 0:
    solve_n(A)
elif num_n == 0:
    solve_p(A)
elif num_p == 1:
    solve1(P, N)
elif num_n == 1:
    solve2(P, N)
else:
    solve3(P, N)

Submission status: Accepted

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

neg = [n for n in A if n < 0]
pos = [n for n in A if n >= 0]

if len(neg) == 0:  # all positive
    x = A.pop(0)
    print(sum(A) - x)
    pivot = A.pop()
    for y in A:
        print(x, y)
        x -= y
    print(pivot, x)
elif len(pos) == 0:  # all negative
    x = A.pop()
    print(x - sum(A))
    for y in A:
        print(x, y)
        x -= y
else:
    print(sum(pos) - sum(neg))
    pivot = pos.pop()
    x = neg.pop()
    for y in pos:
        print(x, y)
        x -= y
    x, pivot = pivot, x
    for y in neg:
        print(x, y)
        x -= y
    print(x, pivot)

Submission status: Accepted

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

log = []

# すべて正
if A[-1] > 0 :
    a = A.pop()
    b = A.pop()
    log.append([a, b])
    A.append(a - b)
# すべて負
elif A[0] < 0 :
    a = A.pop(0)
    b = A.pop()
    log.append([a, b])
    A = [a-b] + A
    
i = 1
while A[i] > 0 :
    a = A.pop()
    log.append([a, A[i]])
    A.append(a-A[i])
    i += 1
    
while i < len(A) :
    log.append([A[0], A[i]])
    A[0] -= A[i]
    i += 1
    
print(A[0])
for l in log :
    print(l[0], l[1])

Submission status: Accepted

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

m = arr[0]
M = arr[-1]
S = []
for a in arr[1:-1]:
  if a > 0:
    S.append(str(m) + ' ' + str(a))
    m -= a
  else:
    S.append(str(M) + ' ' + str(a))
    M -= a
S.append(str(M) + ' ' + str(m))
print(M-m)
[print(s) for s in S]

Submission status: Accepted

Solution code:
N=int(input())
listA=list(map(int,input().split()))
listB=[abs(i) for i in listA]
MAX=max(listA)
MIN=min(listA)
ans=sum(listB)
if MAX<=0:
  print(ans+MAX*2)
elif MIN<=0:
  print(ans)   
else:
  print(ans-MIN*2)
listC=sorted(listA)  
for i in range(len(listA)-2):
  if listC[i+1]>=0:
    print(MIN,listC[i+1])
    MIN=MIN-listC[i+1]
  else:
    print(MAX,listC[i+1])
    MAX=MAX-listC[i+1]
print(MAX,MIN)

Submission status: Accepted

Solution code:
N = int(input())						# 5
A = sorted(list( map(int, input().split()) ))	# 1 2 3 4 5 ...(ソート付き)

ANS=[]

a=A[0]
z=A[-1]

s=0
t=0

for i in A[1:-1]:
	if i>=0:
		ANS.append((a,i))
		a = a-i
	else:
		ANS.append((z,i))
		z = z-i


ANS.append((z,a))

print(z-a)
for a in ANS:
	print(*a)

Submission status: Accepted

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

ans = a[0]
ans_l = []
ans_e = a[-1]

if ans_e >= 0:
    for i in range(1,n-1):
        if a[i] < 0:
            ans_l += [(ans_e, a[i])]
            ans_e -= a[i]
        else:
            ans_l += [(ans, a[i])]
            ans -= a[i]

    ans_l += [(ans_e,ans)]
    ans = ans_e - ans

else:
    ans = ans_e
    for i in range(0,n-1):
        ans_l += [(ans, a[i])]
        ans -= a[i]

print(ans)

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

Submission status: Accepted

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

ans = a[0]
ans_l = []
ans_e = a[-1]

if ans_e >= 0:
    for i in range(1,n-1):
        if a[i] < 0:
            ans_l += [(ans_e, a[i])]
            ans_e -= a[i]
        if a[i] >= 0:
            ans_l += [(ans, a[i])]
            ans -= a[i]

    ans_l += [(ans_e,ans)]
    ans = ans_e - ans

else:
    ans = ans_e
    for i in range(0,n-1):
        ans_l += [(ans, a[i])]
        ans -= a[i]

print(ans)

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

Submission status: Accepted

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