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:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


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


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    A.sort()
    M = A.pop()
    heapq.heapify(A)
    m = heapq.heappop(A)

    ans = []
    while A:
        a = heapq.heappop(A)
        if a < 0:
            ans.append((M, a))
            M -= a
        else:
            ans.append((m, a))
            m -= a

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


def main():
    N = read_int()
    A = read_int_n()
    (slv(N, A))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

import copy

List.sort()

result_list = []
tmp_list = copy.deepcopy(List)

if List[0] > 0:
    if N == 2:
        x = tmp_list[1]
        y = tmp_list[0]
        result_list.append([x,y])
    else:
        x = tmp_list[0]
        y = tmp_list[1]
        result_list.append([x,y])
        del tmp_list[0]
        tmp_list[0] = x - y
        if N >= 4:
            for i in range(N-3):
                x = tmp_list[0]
                y = tmp_list[1]
                result_list.append([x,y])
                del tmp_list[0]
                tmp_list[0] = x - y
        x = tmp_list[1]
        y = tmp_list[0]
        result_list.append([x,y])
        del tmp_list[0]
        tmp_list[0] = x - y                
        
elif List[N-1] <= 0:
    for i in range(N-1):
        x = tmp_list[N-i-1]
        y = tmp_list[N-i-2]
        result_list.append([x,y])
        del tmp_list[N-i-1]
        tmp_list[N-i-2] = x - y
        
else:
    i = 0
    while tmp_list[N-i-2] >= 0:
        x = tmp_list[0]
        y = tmp_list[N-i-1]
        result_list.append([x,y])
        del tmp_list[N-i-1]
        tmp_list[0] = x - y
        i += 1
    for j in range(N-i-1):
        x = tmp_list[N-i-j-1]
        y = tmp_list[0]
        result_list.append([x,y])
        del tmp_list[0]
        tmp_list[N-i-j-2] = x - y

result = x - y

print(result)

for i in range(len(result_list)):
    print(result_list[i][0], result_list[i][1])

Submission status: Accepted

Solution code:
N = int(input())
l = [int(i) for i in input().split(" ")]
l.sort()
M = l[-1]
m = l[0]
ans_l = []
for i in l[1:-1]:
    if i>0:
        ans_l.append(str(m)+" "+str(i))
        m -= i
    else:
        ans_l.append(str(M)+" "+str(i))
        M -= i
ans_l.append(str(M)+" "+str(m))
ans = M - m
print(ans)
[print(j) for j in ans_l]

Submission status: Accepted

Solution code:
n=int(input())
arr=list(map(int,input().split()))
arr=sorted(arr)
cnt1=0
cnt2=0
for i in range(n):
  if arr[i]>=0:
    cnt1+=1
  if arr[i]<=0:
    cnt2+=1
if cnt1==n:
  ans=-arr[0]+sum(arr[1:])
  print(ans)
  tmp=arr[0]
  for i in range(2,n):
    print(tmp,arr[i])
    tmp=tmp-arr[i]
  print(arr[1],tmp)
elif cnt2==n:
  ans=arr[-1]
  for i in range(n-1):
    ans+=abs(arr[i])
  print(ans)
  tmp=arr[-1]
  for i in range(n-1):
    print(tmp,arr[i])
    tmp=tmp-arr[i]
else:
  pos=0
  for i in range(n-1):
    if arr[i]*arr[i+1]<=0:
      pos=i
      break
  pos=pos+1
  ans=0
  for i in range(n):
    ans+=abs(arr[i])
  print(ans)
  for i in range(pos+1,n):
    print(arr[0],arr[i])
    arr[0]=arr[0]-arr[i]
  for i in range(pos):
    print(arr[pos],arr[i])
    arr[pos]=arr[pos]-arr[i]

Submission status: Accepted

Solution code:
import numpy as np


N = int(input())

poss, negs = [], []
npos, nneg = 0, 0
for a in input().split():
    ia = int(a)
    if ia < 0:
        negs.append(ia)
        nneg += 1
    else:
        poss.append(ia)
        npos += 1

# import random
# N = 100000
# npos, nneg = 40000, 60000
# poss = [random.randint(1, 1000) for _ in range(npos)]
# negs = [random.randint(-1000, -1) for _ in range(nneg)]
# 
# poss = []
# negs = [-1, -1, -1]
# npos, nneg = len(poss), len(negs)
# N = npos + nneg

if N == 2:
    a1, a2 = (poss + negs)
    if a1 < a2:
        print(a2 - a1)
        print(a2, a1)
    else:
        print(a1 - a2)
        print(a1, a2)
    exit(0)

if nneg == 0:
    print(sum(poss) - min(poss) * 2)
    argmin = np.array(poss).argmin()
    minpos = poss.pop(argmin)
    pos = poss.pop()
    print(minpos, pos)
    negs.append(minpos - pos)
    npos -= 2
    nneg += 1
elif npos == 0:
    print(-sum(negs) + max(negs) * 2)
    argmax = np.array(negs).argmax()
    maxneg = negs.pop(argmax)  # -1とか
    neg = negs.pop()  # -5とか
    print(maxneg, neg)
    poss.append(maxneg - neg)
    nneg -= 2
    npos += 1
else:
    print(sum(poss) - sum(negs))

if npos > nneg:
    for _ in range(npos - nneg):
        pos, neg = poss.pop(), negs.pop()
        print(neg, pos)
        negs.append(neg - pos)
elif npos < nneg:
    for _ in range(nneg - npos):
        pos, neg = poss.pop(), negs.pop()
        print(pos, neg)
        poss.append(pos - neg)

for i in range(min(nneg, npos) - 1):
    pos, neg = poss.pop(), negs.pop()
    print(neg, pos)
    negs.append(neg - pos)
    pos, neg = poss.pop(), negs.pop()
    print(pos, neg)
    poss.append(pos - neg)

pos, neg = poss.pop(), negs.pop()
print(pos, neg)

Submission status: Accepted

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

ans = ''
stack_neg = []
stack_pos_neg = []
pos_neg_flag = True
ans_flag = False
answer_list = []

A = sorted(A)

while A:
    tmp = A.pop()
    
    if not ans_flag:
        ans = tmp
        ans_flag = True
        continue
        
    if ans_flag and ans < 0 and tmp >= 0:
        tmp2 = ans
        ans = tmp
        tmp = tmp2
    
    if tmp >= 0 and pos_neg_flag and ans_flag:
        stack_pos_neg.append(tmp)

    elif tmp < 0 and pos_neg_flag:
        stack_pos_neg.append(tmp)

        while stack_pos_neg:
            a = stack_pos_neg.pop()
            if not stack_pos_neg:
                stack_pos_neg.append(a)
                pos_neg_flag = False
                break
            b = stack_pos_neg.pop()
            answer_list.append((a, b))
            stack_pos_neg.append(a - b)

    elif tmp >= 0 and not pos_neg_flag:
        a = stack_pos_neg.pop()
        answer_list.append((a, tmp))
        stack_pos_neg.append(a - tmp)

    elif tmp < 0 and not pos_neg_flag:
        stack_neg.append(tmp)
        
if pos_neg_flag:
    stack_pos_neg.append(ans)
    stack_pos = sorted(stack_pos_neg)
    
    ans = stack_pos.pop()
    
    if stack_pos:
        target = stack_pos.pop(0)
    while stack_pos:
        tmp = stack_pos.pop()
        answer_list.append((target, tmp))
        target = target - tmp
    answer_list.append((ans, target))
    ans = ans - target

else:
    tmp = stack_pos_neg.pop()
    answer_list.append((ans, tmp))
    ans = ans - tmp
    
    while stack_neg:
        tmp = stack_neg.pop()
        answer_list.append((ans, tmp))
        ans = ans - tmp

print(ans)

if N != 1:
    for answer in answer_list:
        i, j = answer
        print(i, j)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = list(map(int, input().split()))
plus = 0
minus = 0
for i in range(N):
    if A[i] >= 0:
        plus += 1
    else:
        minus += 1
bb = deque(sorted(A))
x = [0]*(N-1)
y = [0]*(N-1)
for i in range(N-1):
    if len(bb) == 2:
        l = bb.popleft()
        r = bb.pop()
        if l > r:
            ret = l-r
            x[i] = l
            y[i] = r
        else:
            ret = r - l
            x[i] = r
            y[i] = l
    else:
        l = bb.popleft()
        r = bb.pop()

        if plus > minus:
            ret = l - r
            x[i] = l
            y[i] = r
            plus -= 1
        else:
            ret = r - l
            x[i] = r
            y[i] = l
            minus -= 1
    if ret > 0:
        bb.append(ret)
    else:
        bb.appendleft(ret)
print(bb.pop())
for i in range(N-1):
    print(x[i], y[i])

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
ans=[]
R=a.pop()
L=a.pop(0)
s=L
if a:
    while a[-1]>0:
        r=a.pop()
        ans.append([s,r])
        s=s-r
        if not a:break
ans.append([R,s])
s=R-s
while a:
    L=a.pop()
    ans.append([s,L])
    s=s-L
print(s)
for x in ans:
    print(*x)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    A = sorted(A)
    A_M = sorted(A)
    A_M[0] *= -1
    start = 0
    if N == 2:
        print(max(A) - min(A))
        print('{} {}'.format(max(A), min(A)))
        return
    for i in range(1, N-1):
        if A_M[i] < 0:
            A_M[i] *= -1
            start = i
    M = sum(A_M)
    print(M)
    if start == 0:
        for i in range(1, N):
            if i < N-1:
                if i == 1:
                    x = A[0]
                    y = A[1]
                else:
                    x = tmp
                    y = A[i]
            else:
                x = A[-1]
                y = tmp
            tmp = x - y
            print('{} {}'.format(x, y))
    elif start == N - 2:
        for i in range(1, N):
            if i == 1:
                x = A[-1]
                y = A[start]
            else:
                x = tmp
                y = A[start-i+1]
            tmp = x - y
            print('{} {}'.format(x, y))
    else:
        for i in range(1, N):
            if i == 1:
                x = A[start]
                y = A[start+1]
            elif 1 < i < N - 1 - start:
                x = tmp
                y = A[start+i]
            elif i == N - 1 - start:
                x = A[-1]
                y = tmp
            else:
                x = tmp
                y = A[start-(i-(N-1-start))]
            tmp = x - y
            print('{} {}'.format(x, y))
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

tasug=[]
hikug=[]
for i in range(n):
  if a[i]<0:
    hikug.append(a[i])
  else:
    tasug.append(a[i])

if len(hikug)==0:
  tasug.sort()
  ans=sum(tasug)-2*tasug[0]
  print(ans)
  for i in range(len(tasug)-1):
    if i ==0:
      print(tasug[0],tasug[1])
      a=tasug[0]-tasug[i]
    elif i==1:
      continue
    else:
      print(a,tasug[i])
      a=a-tasug[i]
  if not n==2:
    print(tasug[len(tasug)-1],a)
  
  
elif len(tasug)==0:
  hikug.sort()
  ans=-sum(hikug)+2*hikug[n-1]
  print(ans)
  for i in range(n-1):
    if i ==0:
      a=hikug[n-1]

    print(a,hikug[i])
    a=a-hikug[i]

else:
  ans=sum(tasug)-sum(hikug)
  print(ans)
  if len(tasug)==1:
    for i in range(len(hikug)):
      if i ==0:
        print(tasug[0],hikug[i])
        a=tasug[0]-hikug[i]
      else:
        print(a,hikug[i])
        a=a-hikug[i]
  else:
    for i in range(len(tasug)-1):
      if i ==0:
        print(hikug[0],tasug[i])
        a=hikug[0]-tasug[i]
      else:
        print(a,tasug[i])
        a=a-tasug[i]

    print(tasug[len(tasug)-1],a)
    a=tasug[len(tasug)-1]-a
  
    for i in range(1,len(hikug)):
      print(a,hikug[i])
      a=a-hikug[i]

Submission status: Accepted

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

ans = []
f = 0
l = N-1
s = 0

if N == 2:
    ans.append([A[l], A[f]])
    s = A[l] - A[f]
    f += 1
    l -= 1
else:
    hasPlus = True if A[N-2] >= 0 else False
    if hasPlus:
        # make minus
        ans.append([A[f], A[l]])
        s = A[f] - A[l]
        f += 1
        l -= 1
        while f <= l:
            if f == l or A[l-1] < 0:
                # choose plus make plus
                ans.append([A[l], s])
                s = A[l] - s
                l -= 1
                break
            # choose plus make minus
            ans.append([s, A[l]])
            s = s - A[l]
            l -= 1
    else:
        # make plus
        ans.append([A[l], A[f]])
        s = A[l] - A[f]
        f += 1
        l -= 1

# choose minus make plus
while f <= l:
    ans.append([s, A[l]])
    s = s - A[l]
    l -= 1

print(s)
for x, y in ans:
    print(x, y)

Submission status: Accepted

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

n_pos = len([a for a in A if a > 0])
operations = []
if n_pos == 0:
    pos = [A[-1]]
    neg = A[:-1]
elif n_pos == N:
    pos = A[1:]
    neg = A[:1]
else:
    pos = [a for a in A if a > 0]
    neg = [a for a in A if a <= 0]
if len(pos) >= 2:
    tmp = neg[0]
    for i in range(len(pos)-1):
        operations.append((tmp, pos[i]))
        tmp = tmp - pos[i]
    operations.append((pos[-1], tmp))
    tmp = pos[-1] - tmp
    for i in range(1, len(neg)):
        operations.append((tmp, neg[i]))
        tmp = tmp - neg[i]
else:
    tmp = pos[0]
    for i in range(len(neg)):
        operations.append((tmp, neg[i]))
        tmp = tmp - neg[i]
print(tmp)
for o in operations:
    print("{} {}".format(o[0], o[1]))

Submission status: Accepted

Solution code:
import sys
N = int(input())
A = [int(i) for i in input().split()]
A.sort()
a = A[0]
b = A[-1]
if N == 2:
    print(A[1]-A[0])
    print(A[1],A[0])
    sys.exit()
ans = []
for x in A[1:-1]:
    if x <= 0:
        ans.append([b, x])
        b = b - x
    else:
        ans.append([a, x])
        a = a - x
ans.append([b,a])
M = b-a
print(M)
for x in ans:
    print(x[0], x[1])

Submission status: Accepted

Solution code:
import numpy as np

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

A = np.array(A)

A = np.sort(A)

B = np.copy(A)
if n == 2:
    print(A[1] - A[0])
    print(A[1], A[0])

elif A[0] <= 0 and A[n-1] >= 0:
    for i in range(n-1):
        A[i] = min(A[i], -A[i])

    print(np.sum(A[:-1]) * -1 + A[n-1])

    k = n - 2
    a = B[0]
    while B[k] >= 0:
        print(a, B[k])
        a = a - B[k]
        k -= 1
        if k == 0:
            break

    b = B[n-1]

    while k != 0:
        print(b, B[k])
        b = b - B[k]
        k -= 1

    print(b, a)

elif A[n-1] < 0:
    A[n-1] = A[n-1] - A[n-2]
    A[n-2] = 0
    for i in range(n-1):
        A[i] = min(A[i], -A[i])

    print(np.sum(A[:-1]) * -1 + A[n-1])

    a = B[n-1]
    for i in range(n-1):
        print(a, B[i])
        a = a - B[i]

else:
    A[0] = A[0] - A[1]
    A[1] = 0
    for i in range(n-1):
        A[i] = min(A[i], -A[i])

    print(np.sum(A[:-1]) * -1 + A[n-1])

    k = n - 2
    a = B[0]
    while B[k] >= 0:
        print(a, B[k])
        a = a - B[k]
        k -= 1
        if k == 0:
            break

    b = B[n-1]

    while k != 0:
        print(b, B[k])
        b = b - B[k]
        k -= 1

    print(b, a)

Submission status: Accepted

Solution code:
from collections import Counter
import sys

def debug(*a):
    print(*a, file=sys.stderr)

def solve(N, A):
    A = sorted(A)
    debug("A =", A)
    assert len(A) == N
    s = []
    if all(a < 0 for a in A):
        x = A[-1]
        for i in range(0, N-1):
            s.append((x, A[i]))
            x -= A[i]
        print(x)
        for x in s:
            print(*x)
        return
    if all(a >= 0 for a in A):
        x = A[0]
        for i in range(2, N):
            s.append((x, A[i]))
            x -= A[i]
        s.append((A[1], x))
        print(A[1] -x)
        for x in s:
            print(*x)
        return 

    pos = 0
    for i in range(N):
        if A[i] >= 0:
            pos =i
            break
    #print("A =", A)
    x = A[pos] # x > 0
    for i in range(pos-1):
        s.append(("+", x, A[i]))
        x -= A[i]
    
    y = A[pos-1] # y < 0
    for i in range(pos+1, N):
        s.append(("-", y, A[i]))
        y -= A[i] # y < 0
    s.append(("=", x, y))
    #print("N =", x-y)
    print(x-y)
    assert(len(s) == N-1)
    for x in s:
        debug(*x)
        print(*x[1:])

def main():
    N = int(input())
    A = [int(x) for x in input().split()]

    solve(N, A)

main()

Submission status: Accepted

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

A.sort()

L = [a for a in A if a <= 0]
R = [a for a in A if a > 0]

ans = []

if L != [] and R != []:
    low = L[0]
    for r in R[:-1]:
        ans.append([low, r])
        low -= r

    up = R[-1]
    for l in L[1:]:
        ans.append([up, l])
        up -= l

    ans.append([up, low])
    ans.append([up - low])

elif L == []:
    low, up = R[0], R[-1]
    for r in R[1:-1]:
        ans.append([low, r])
        low -= r
    ans.append([up, low])
    ans.append([up - low])

elif R == []:
    low, up = L[0], L[-1]
    for l in L[1:-1]:
        ans.append([up, l])
        up -= l
    ans.append([up, low])
    ans.append([up - low])

print(*ans[-1])
for a in ans[:-1]:
    print(*a)

Submission status: Accepted

Solution code:
import bisect

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

i = bisect.bisect_left(A, 0)
j = bisect.bisect_right(A, 0)
if i == j:
    if i == 0:
        negatives = A[:1]
        positives = A[1:]
    elif i == N:
        negatives = A[:-1]
        positives = A[-1:]
    else:
        negatives = A[:i]
        positives = A[i:]

else:
    m = max((i+j)//2, 1)
    negatives = A[:m]
    positives = A[m:]


score = sum(positives) - sum(negatives)
print(score)

def it():

    def balanced(pos, neg):
        y = neg.pop()
        x = pos.pop()
        yield (x,y)
        y = x-y
        while pos and neg:
            x = neg.pop()
            yield (x,y)
            y = x-y
            x = pos.pop()
            yield (x,y)
            y = x-y

    if len(positives) < len(negatives):

        x = positives.pop()

        while len(positives)+1 < len(negatives):
            y = negatives.pop()
            yield (x,y)
            x -= y
        positives.append(x)
    elif len(positives) > len(negatives):
        x = negatives.pop()

        while len(negatives)+1 < len(positives):
            y = positives.pop()
            yield (x,y)
            x -= y
        negatives.append(x)

    for x,y in balanced(positives, negatives):
        yield x,y


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

Submission status: Accepted

Solution code:
import sys
N = int(input())
A = [int(i) for i in input().split()]
A.sort()
a = A[0]
b = A[-1]
if N == 2:
    print(A[1]-A[0])
    print(A[1],A[0])
    sys.exit()
ans = []
for x in A[1:-1]:
    if x <= 0:
        ans.append([b, x])
        b = b - x
    else:
        ans.append([a, x])
        a = a - x
ans.append([b,a])
M = b-a
print(M)
for x in ans:
    print(x[0], x[1])

Submission status: Accepted

Solution code:
# C
if __name__=='__main__':
    N = int(input())
    A = list(map(int,input().split()))
    A.sort()
    k = N-1
    x = 0
    for i in range(1,N):
        if A[i]>0:
            k = i
            break
    M = sum(A[k:])-sum(A[:k])
    print(M)
    x = A[k-1]
    for i in range(k,N-1):
        print('{} {}'.format(x,A[i]))
        x = x - A[i]
    print('{} {}'.format(A[N-1],x))
    x = A[N-1] - x
    for i in range(k-1):
        print('{} {}'.format(x,A[i]))
        x = x -A[i]

Submission status: Accepted

Solution code:
n = input()
a_ls = list(map(int, input().split()))
a_ls.sort()
min_value = a_ls.pop(0)
max_value = a_ls.pop(len(a_ls)-1)
output_ls = []
for i in range(len(a_ls)):
    hoge = []
    if a_ls[i] > 0:
        hoge.append(min_value)
        hoge.append(a_ls[i])
        output_ls.append(hoge)
        min_value = min_value - a_ls[i]
    else:
        hoge.append(max_value)
        hoge.append(a_ls[i])
        output_ls.append(hoge)
        max_value = max_value - a_ls[i]
hoge = []
hoge.append(max_value)
hoge.append(min_value)
output_ls.append(hoge)
print(max_value - min_value)
for j in range(len(output_ls)):
    print(str(output_ls[j][0]) + ' ' + str(output_ls[j][1]))

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 n > 2:
    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]

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

print(ans)

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

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
A = list(map(int, input().split()))
A.sort()
d = deque(A)
if A[0] <= 0 and A[-1] >= 0:
    print(sum(map(abs, A)))
    while len(d) > 2:
        while d[1] < 0:
            x = d.pop()
            y = d.popleft()
            print(x, y)
            d.append(x - y)
        x = d.popleft()
        y = d.pop()
        if d:
            print(x, y)
        else:
            print(y, x)
        d.appendleft(x - y)
    if len(d) >= 2:
        print(d[1], d[0])

elif A[0] > 0:
    print(sum(A) - 2 * A[0])
    x = d.popleft()
    y = d.pop()
    if not d:
        print(y, x)
    else:
        print(x, y)
    d.appendleft(x - y)
    while len(d) > 2:
        x = d.popleft()
        y = d.pop()
        print(x, y)
        d.appendleft(x - y)
    if len(d) >= 2:
        print(d[1], d[0])
else:
    print(-sum(A) + 2 * A[-1])
    x = d.pop()
    y = d.popleft()
    print(x, y)
    d.append(x - y)
    while len(d) > 2:
        while d[1] < 0 and len(d) > 2:
            x = d.pop()
            y = d.popleft()
            print(x, y)
            d.append(x - y)
        x = d.pop()
        y = d.popleft()
        print(x, y)
        d.appendleft(x - y)
    if len(d) >= 2:
        print(d[1], d[0])

Submission status: Accepted

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

Submission status: Accepted

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

a.sort()
l=[]
sum=-a[0]+a[n-1]
for i in range(n-2):
    sum+=abs(a[i+1])
print(sum)

x=a[n-1]-a[0]
for i in range(n-1):
    if i==0:
        l.append([a[n-1],a[0]])
    else:
        if a[i]<0:
            l.append([x,a[i]])
            x+=abs(a[i])
        else:
            s=l[i-1][0]
            t=l[i-1][1]
            l[i-1][0]=t
            l[i-1][1]=s
            l.append([a[i],-x])
            x+=a[i]

for y in l:
    print(y[0],y[1])

Submission status: Accepted

Solution code:
import sys,heapq
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True # and False
def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
a.sort()
d = deque(a)
seq = []
for i in range(n-2):
    l = d.popleft()
    r = d.pop()
    r2 = d.pop()
    if r2>0:
        seq.append((l,r2))
        d.appendleft(l-r2)
        d.append(r)
    else:
        seq.append((r,r2))
        d.appendleft(l)
        d.append(r-r2)

bb = d.pop()
aa = d.pop()
seq.append((bb,aa))
print(bb-aa)
for i in range(n-1):
    print("{} {}".format(seq[i][0], seq[i][1]))

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = [int(i) for i in input().split()]

pos = [a for a in A if a >= 0]
neg = [a for a in A if a < 0]
# zero = [a for a in A if a == 0]

pos.sort()
neg.sort()

pd = deque(pos)
nd = deque(neg)

buf = []

while len(pd) + len(nd) > 2:  # more 3
    # もし負の数が無かったら追加
    if len(nd) == 0:
        y, x = pd.pop(), pd.popleft()
        buf.append((x, y))
        nd.append(x - y)
        continue
    # もし正の数が無かったら追加
    if len(pd) == 0:
        x, y = nd.pop(), nd.popleft()
        buf.append((x, y))
        pd.append(x - y)
        continue
    # 正の数が1より大きかったら減らす
    if len(pd) > 1:
        x, y = nd.pop(), pd.pop()
        buf.append((x, y))
        nd.append(x - y)
        continue
    # 正の数がちょうど1だったらどんどん正の数を大きくする
    if len(pd) == 1:
        x, y = pd.pop(), nd.pop()
        buf.append((x, y))
        pd.append(x - y)
        continue

merge = []
merge.extend(nd)
merge.extend(pd)

val = merge[1] - merge[0]
buf.append((merge[1], merge[0]))

# print
print(val)
for b in buf:
    print(b[0], b[1])

Submission status: Accepted

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

a.sort()
if a[0] >= 0:
    m = sum(a[1:]) - a[0]
    print(m)
    tmp = a[0]
    for i in range(1, n-1):
        print(tmp, a[i])
        tmp -= a[i]
    print(a[n-1], tmp)
elif a[-1] <= 0:
    m = -sum(a[:-1]) + a[-1]
    print(m)
    tmp = a[n-1]
    for i in range(n-1):
        print(tmp, a[i])
        tmp -= a[i]
else:
    m = 0
    pos = []
    neg = []
    for ai in a:
        m += abs(ai)
        if ai >= 0:
            pos.append(ai)
        else:
            neg.append(ai)
    print(m)
    tmp = 0
    ni = 0
    pi = 0

    if len(pos) > 1:
        print(neg[ni], pos[pi])
        tmp = neg[ni] - pos[pi]
        ni += 1
        pi += 1

        while pi < len(pos) - 1:
            print(tmp, pos[pi])
            tmp = tmp - pos[pi]
            pi += 1
        print(pos[pi], tmp)
        tmp = pos[pi] - tmp
        while ni < len(neg):
            print(tmp, neg[ni])
            tmp -= neg[ni]
            ni += 1
    else:
        print(pos[pi], neg[ni])
        tmp = pos[pi] - neg[ni]
        ni += 1
        while ni < len(neg):
            print(tmp, neg[ni])
            tmp -= neg[ni]
            ni += 1

Submission status: Accepted

Solution code:
n = int(input())
x = list(map(int,input().split()))
#x = sorted(list(map(int,input().split())),reverse=True)
#nmax = max(x)
#ans = 2*nmax-sum(x)
lst = []

  
nmi = min(x)
nma = max(x)
del x[x.index(nmi)]
del x[x.index(nma)]

mainus = [i for i in x if i < 0]
plus = [i for i in x if i >= 0]
for i in mainus:
  lst.append(str(nma)+" "+str(i))
  nma -= i
for i in plus:
  lst.append(str(nmi)+" "+str(i))
  nmi -= i
lst.append(str(nma)+" "+str(nmi))
print(nma-nmi)
for i in lst:
  print(i)
"""
while max(x) > -1 and len(x) > 1:
  mi = min(x)
  ma = max(x)
  lst.append(str(mi)+" "+str(ma))
  del x[x.index(mi)]
  del x[x.index(ma)]
  x.append(mi - ma)

for i in range(len(x)):
  lst.append(str(nma)+" "+str(i))
  nma += i
print(nmi - nma)
for i in range(len(lst)):
  print(lst[i])
print(nmi,nma)
"""

Submission status: Accepted

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from sys import stdin
from collections import deque


def main():
  # input
  N = int(input())
  An = list(map(int, stdin.readline().rstrip().split()))
  An = sorted(An)
  Bn_p,Bn_n = [deque(),deque()]
  for a in An:
    if a >= 0:
      Bn_p.append(a)
    else:
      Bn_n.append(a)
  Bn_n = deque(sorted(Bn_n,reverse=True))

  xy = deque()
  ans = 0
  if len(Bn_p)==0:
    ## 負数のみ
    ans = Bn_n[0]
    for i in range(1,len(Bn_n)):
      x = ans
      y = Bn_n[i]
      xy.append([x,y])
      ans = x-y
  elif len(Bn_n)==0:
    ## 正数のみ
    ans = Bn_p[0]
    for i in range(1,len(Bn_p)-1):
      x = min([Bn_p[i],ans])
      y = max([Bn_p[i],ans])
      xy.append([x,y])
      ans = x-y
    xy.append([Bn_p[-1],ans])
    ans = Bn_p[-1]-ans
  else:
    ## 正負混在
    ans_n = Bn_p.popleft()
    ans_p = Bn_n.popleft()
    ### 正数はminを作り続ける
    for i in range(len(Bn_p)):
      x = ans_p
      y = Bn_p[i]
      xy.append([x,y])
      ans_p = x-y

    Bn_n.append(ans_p)
    ### 負数はmaxを作り続ける
    for i in range(len(Bn_n)):
      x = ans_n
      y = Bn_n[i]
      xy.append([x,y])
      ans_n = x-y
    ans = ans_n

  print(ans)
  for x,y in xy:
    print(x,y)

if __name__ == "__main__":
  main()

Submission status: Accepted

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

if n == 2:
    print(a[1] - a[0])
    print("{} {}".format(a[1], a[0]))
    exit()

if a[0] <= 0 and 0 <= a[-1]:
    import bisect
    print(sum(map(lambda x: abs(x), a)))
    x0 = bisect.bisect_left(a,0)

    # 0以下から0以上をひいていく（一番大きいものを除く）
    if a[-2] >= 0:
        if x0 == 0:
            x0 += 1
        print("{} {}".format(a[0], a[x0]))
        res = a[0] - a[x0]

        for x in a[x0+1:-1]:
            print("{} {}".format(res, x))
            res -= x
    else:
        res = a[0]

    # 一番大きいものから上のものと負の数を引いていく
    print("{} {}".format(a[-1], res))
    res = a[-1] - res
    for x in a[1:x0]:
        print("{} {}".format(res,x))
        res -= x

elif a[0] > 0:
    print(sum(a) - 2*a[0])

    print("{} {}".format(a[0],a[1]))
    res = a[0] - a[1]
    for x in a[2:-1]:
        print("{} {}".format(res, x))
        res -= x
    
    print("{} {}".format(a[-1], res))
else:
    print(-sum(a) + 2*a[-1])

    print("{} {}".format(a[-1],a[-2]))
    res = a[-1] - a[-2]
    for x in a[:-2]:
        print("{} {}".format(res, x))
        res -= x