Problem:


Score : 500 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 10^5

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

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

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

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

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

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

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

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

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0



Sample input:
3
1 -1 2


Sample output:
4
-1 1
2 -2

Submission status: Accepted

Solution code:
import sys
INF = 10 ** 11
MOD = 10 ** 9 + 7
from collections import deque
sys.setrecursionlimit(100000000)
from heapq import heapify,heappush,heappop   

def main():
    n = int(input())
    a = list(map(int,input().split()))
    m = []
    p = []
    z = 0
    for num in a:
        if num < 0:
            m.append(num)
        elif num > 0:
            p.append(num)
        else:
            z += 1
    
    ans = []
    
    if z == n:
        print(0)
        for i in range(n - 1):
            print(0,0)
        return

    if len(p) == 0:
        if z:
            num1 = 0
            z -= 1
        else:
            m.sort()
            num1 = m[-1]
            m.pop()
        for i in range(len(m)):
            ans.append((num1,m[i]))
            num1 -= m[i]
    
    elif len(m) == 0:
        if z:
            num1 = 0
            z -= 1
            idx = 0
        else:
            p.sort()
            num1 = p[0]
            idx = 1
        for i in range(idx,len(p) - 1):
            ans.append((num1,p[i]))
            num1 -= p[i]
        ans.append((p[-1],num1))
        num1 = p[-1] - num1
    
    elif len(p) * len(m) > 0:
        num1 = p[-1]
        p.pop()
        num2 = m[-1]
        m.pop()
        for i in range(len(m)):
            ans.append((num1,m[i]))
            num1 -= m[i]
        for i in range(len(p)):
            ans.append((num2,p[i]))
            num2 -= p[i]
        ans.append((num1,num2))
        num1 -= num2
    
    for i in range(z):
        ans.append((num1,0))
    print(num1)
    for i in range(n - 1):
        print(*ans[i])

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
A.sort()
m=A[0]
if m>=0:
    M=sum(A)-2*m
    print(M)
    s=A[0]
    for i in range(0,N-1):
        if i!=N-2:
            print(s,A[i+1])
            s-=A[i+1]
        else:
            print(A[N-1],s)
else:
    if A[N-1]>0:
        start=0
        end=N-1
        while end-start>1:
            test=(end+start)//2
            if 0>A[test]:
                start=test
            else:
                end=test
        if 0>A[end]:
            mid=end
        else:
            mid=start
        M=sum(abs(A[i]) for i in range(0,N))
        print(M)
        s=A[0]
        for i in range(mid+1,N):
            if i!=N-1:
                print(s,A[i])
                s-=A[i]
            else:
                print(A[N-1],s)
                s=A[N-1]-s
        for i in range(1,mid+1):
            print(s,A[i])
            s-=A[i]
    else:
        M=-sum(A)+2*A[N-1]
        print(M)
        s=A[N-1]
        for i in range(0,N-1):
            print(s,A[i])
            s-=A[i]

Submission status: Accepted

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


def solve(N: int, A: "List[int]"):
    A.sort()

    if all([a <= 0 for a in A]):
        print(A[-1]-(sum(A)-A[-1]))

        for i in range(N-1):
            print(A[-1],A[i])
            A[-1] -= A[i]
        return
    if all([a >= 0 for a in A]):
        print(sum(A)-A[0]-A[0])
        for i in range(1,N-1):
            print(A[0],A[i])
            A[0] -= A[i]
        print(A[-1],A[0])
        return
    
    answer = 0
    plus = []
    minus = []
    for i in range(N):
        if A[i] >= 0:
            plus.append(A[i])
        else:
            minus.append(A[i])
        answer += abs(A[i])
    print(answer)
    
    while len(plus)>1:
        p = plus.pop()
        m = minus.pop()
        minus.append(m-p)
        print(m,p)
    
    while minus:
        m = minus.pop()
        print(plus[0],m)
        plus[0] -= m
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

    a = list(sorted(a))
    min_a = a.pop(0)
    max_a = a.pop(-1)

    pos_a = filter(lambda x: x >= 0, a)
    neg_a = filter(lambda x: x < 0, a)
    procedure = []
    
    state = min_a
    for _a in pos_a:
        procedure.append((state, _a))
        state -= _a

    procedure.append((max_a, state))
    state = max_a - state

    for _a in neg_a:
        procedure.append((state, _a))
        state -= _a

    print(state)
    for t in procedure:
        print(t[0], t[1])

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

if n==2:
    print(max(al)-min(al))
    print(max(al),min(al))
    exit()

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

pos.sort()
neg.sort(reverse=True)
res = []

if len(pos)==0:
    x = neg[0]
    for a in neg[1:]:
        res.append((x,a))
        x -= a
elif len(neg)==0:
    x = pos[0]
    for a in pos[1:-1]:
        res.append((x,a))
        x -= a
    res.append((pos[-1],x))
    x = pos[-1]-x
else:
    p = pos[0]
    pos = pos[1:]

    x = neg[0]
    neg = neg[1:]

    for a in pos:
        res.append((x,a))
        x -= a
    res.append((p,x))
    x = p - x
    for a in neg:
        res.append((x,a))
        x -= a


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

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int, input().split()))
A.sort()
P=sum([1 for a in A if a >= 0])
Q=N-P
if P==0:
  P=1
  Q=N-1
elif Q==0:
  P=N-1
  Q=1
ans=[]
for y in range(Q, N-1):
  ans.append((A[0], A[y]))
  A[0]=A[0]-A[y]

for y in range(Q):
  ans.append((A[N-1],A[y]))
  A[N-1]=A[N-1]-A[y]

print(A[N-1])
for x in ans:
  print(*x)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    neg = []
    pos = []
    for v in a:
        if v < 0:
            neg.append(v)
        else:
            pos.append(v)
    ans = []
    neg.sort()
    x, y = 0, len(neg)-1
    if len(pos) == 0:
        ans.append([neg[y], neg[x]])
        p = neg[y] - neg[x]
        pos.append(p)
        x += 1
        y -= 1
    for i in range(x, y):
        ans.append([pos[0], neg[i]])
        pos[0] -= neg[i]
    if y-x+1 > 0:
        pos.append(neg[y])
    pos.sort()
    for i in range(len(pos)-2):
        ans.append([pos[i], pos[i+1]])
        pos[i+1] = pos[i] - pos[i+1]
    if len(pos) > 1:
        ans.append([pos[len(pos)-1], pos[len(pos)-2]])
        pos[len(pos)-1] = pos[len(pos)-1] - pos[len(pos)-2]
    print(pos[len(pos)-1])
    for p, q in ans:
        print(p, q)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort()
a = A[0]
b = A[-1]
xy = []
for i in range(1, N-1):
    if A[i] > 0:
        xy.append((a, A[i]))
        a -= A[i]
    else:
        xy.append((b, A[i]))
        b -= A[i]
xy.append((b, a))
print(b-a)
for x, y in xy:
    print(x, y)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
from operator import itemgetter

def main():
    N = int(input())
    a = list(map(int,input().split()))
    posi,nega = [],[]
    for num in a:
        if num >= 0:
            posi.append(num)
        else:
            nega.append(num)
    
    posi.sort()
    nega.sort(reverse=True)
    ans = []
    if len(posi) == 0:
        a = nega[0]
        for i in range(N-1):
            ans.append((a,nega[i+1]))
            a -= nega[i+1]
    elif len(nega) == 0:
        if len(posi) == 2:
            ans.append((max(posi),min(posi)))
        else:
            a = posi[0]
            for i in range(N-2):
                ans.append((a,posi[i+1]))
                a -= posi[i+1]
            ans.append((posi[-1],a))
    else:
        pl,nl = len(posi),len(nega)
        a = posi[0]
        for i in range(pl-1):
            ans.append((nega[0],posi[i+1]))
            nega[0] -= posi[i+1]
        for i in range(nl):
            ans.append((a,nega[i]))
            a -= nega[i]
            
    print(ans[-1][0]-ans[-1][1])
    for x,y in ans:
        print(x,y)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from heapq import heapify,heappop,heappush
n = int(input())
a = list(map(int,input().split()))
if max(a) > 0 and min(a) < 0:
  hp = []
  hn = []
  heapify(hp)
  heapify(hn)
  ans = 0
  for i in range(n):
    if a[i] >= 0:
      heappush(hp,a[i])
      ans += a[i]
    else:
      ans -= a[i]
      heappush(hn,a[i])
  print(ans)
  while hp and hn:
    p = heappop(hp)
    q = heappop(hn)
    if hn:
      print(p,q)
      heappush(hp,p-q)
    elif hp:
      print(q,p)
      heappush(hn,q-p)
    else:
      print(p,q)
elif min(a) >= 0:
  ans = sum(a)-2*min(a)
  print(ans)
  heapify(a)
  while a:
    p = heappop(a)
    if a:
      q = heappop(a)
      if a:
        print(p,q)
        heappush(a,p-q)
      else:
        print(q,p)
    else:
      break
elif max(a) <= 0:
  ans = -sum(a)+2*max(a)
  a = [-a[i] for i in range(n)]
  heapify(a)
  print(ans)
  while a:
    p = heappop(a)
    if a:
      q = heappop(a)
      if a:
        print(-p,-q)
        heappush(a,p-q)
      else:
        print(-p,-q)
    else:
      break

Submission status: Accepted

Solution code:
import heapq
from collections import defaultdict
N = int(input())
nums  = list(map(int, input().split(" ")))
# 正の数、負の数の個数で操作をコントロール？
p_count = 0
m_count = 0
pos = []
minus = []
for num in nums:
    if num < 0:
        m_count += 1
        minus.append(num)
    else:
        p_count += 1
        pos.append(num)
pos.sort()
minus.sort() #小さい順番
途中式 = []
if N == 2:
    x = max(nums) 
    y = min(nums)
    print(max(nums) - min(nums))
    print(x, y)
else:
    #正の数を一つにして、そこから引きまくる
    if m_count == 0: #マイナスが無かったら作る
        x = min(pos)
        y = max(pos)
        途中式.append((x, y))
        minus.append(x - y)
        pos.remove(x)
        pos.remove(y)
        p_count -=2
        m_count += 1

    if p_count > 1: # 正が複数あったら、マイナスから引くことで減らしていく
        for i in range(p_count - 1):
            #マイナスから正が1個になるまで引いていく
            x = minus.pop()
            y = pos.pop()
            途中式.append((x,y))
            minus.append(x- y)
    elif p_count == 0 : #正が一つも無かったら、作る
        x = minus.pop()
        y = minus.pop()
        途中式.append((x, y))
        pos.append(x - y)

    x = pos.pop()
    for i in minus:
        y = i
        途中式.append((x, y))
        x -=y
    print(x)
    for temp in 途中式:
        x,y = temp
        print(x,y)

Submission status: Accepted

Solution code:
#解説参照
#構成が無理
#テストどうやってんだろ
n = int(input())
a = list(map(int, input().split( )))

a.sort()
from bisect import bisect_left

j = bisect_left(a,0)
if j==0:
    j+=1
elif j==n:
    j-=1
print(sum(a[j:])-sum(a[:j]))
for i in range(j,n-1):
    print(a[0],a[i])
    a[0]-=a[i]

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort()
P = sum([1 for a in A if a >= 0])
Q = N - P
if P == 0:
    P = 1
    Q = N - 1
elif Q == 0:
    P = N - 1
    Q = 1

# print(P, Q)
ans = []
for y in range(Q, N - 1):
    ans.append((A[0], A[y]))
    A[0] = A[0] - A[y]

for y in range(Q):
    ans.append((A[N - 1], A[y]))
    A[N - 1] = A[N - 1] - A[y]

print(A[N - 1])
for x in ans:
    print(*x)

Submission status: Accepted

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

ans = []
A.sort()
if A[0] >= 0:
    ans.append([A[0], A[1]])
    A[1] = A[0]-A[1]
    A.pop(0)
elif A[-1] <= 0:
    ans.append([A[-1], A[-2]])
    A[-2] = A[-1]-A[-2]
    A.pop(N-1)
for i in range(1, len(A)-1):
    if A[i] < 0:
        ans.append([A[-1], A[i]])
        A[-1] -= A[i]
    else:
        ans.append([A[0], A[i]])
        A[0] -= A[i]
if N > 2:
    ans.append([A[-1], A[0]])
print(A[-1]-A[0])
for a in ans:
    print(*a)

Submission status: Accepted

Solution code:
from sys import stdin
n = int(stdin.readline().rstrip())
li = list(map(int,stdin.readline().rstrip().split()))
li.sort(reverse=True)
plus = []
minus = []
lin = []
for i in li:
    if i < 0:
        minus.append(i)
    else:
        plus.append(i)
if not plus:
    x = minus[0]
    for i in range(1,n):
        y = minus[i]
        lin.append([x,y])
        x -= y
    print(x)
    for i in lin:
        print(*i)
elif not minus:
    x = plus[-1]
    for i in range(1,n-1):
        y = plus[i]
        lin.append([x,y])
        x -= y
    lin.append([plus[0],x])
    print(plus[0]-x)
    for i in lin:
        print(*i)
else:
    x = minus[-1]
    y = plus[0]
    for i in range(len(minus)-1):
        lin.append([y,minus[i]])
        y -= minus[i]
    for i in range(1,len(plus)):
        lin.append([x,plus[i]])
        x -= plus[i]
    lin.append([y,x])
    print(y-x)
    for i in lin:
        print(*i)

Submission status: Accepted

Solution code:
N,*A=map(int, open(0).read().split())
A.sort()
m,M=A[0],A[-1]
B=A[1:-1]
ans=[]
for b in B:
    if b>=0:
        ans.append((m,b))
        m-=b
    else:
        ans.append((M,b))
        M-=b
ans.append((M,m))
print(M-m)
for x,y in ans:
    print(x,y)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

if A[0]<=0 and A[-1]<=0:
    ans = sum(map(abs, A[:-1]))+A[-1]
    A.reverse()

    r = 1
    a, b = A[0], A[1]
    t = []
    
    while 1:
        x, y = (a, b) if a>b else (b, a)
        t.append((x, y))
        r += 1
        if not r<N:
            break
        a, b = x-y, A[r]

elif A[0]>=0 and A[-1]>=0:
    ans = sum(A[1:])-A[0]

    r = 1
    a, b = A[0], A[1]
    t = []
    
    while 1:
        x, y = (a, b) if a<b else (b, a)
        t.append((x, y))
        
        r += 1
        if not r<N:
            break
        a, b = x-y, A[r]
    a, b = t[-1]
    t[-1] = (b, a)


else:
    ans = sum(map(abs, A))
    p = bisect_left(A, 0)
    t = []
    s = []

    a = A[p-1]
    for i in range(p, N-1):
        b = A[i]
        t.append((a, b))
        a = a - b
        
    c = A[N-1]
    for i in ([a]+A[:p-1]):
        t.append((c, i))
        c = c-i

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

Submission status: Accepted

Solution code:
n = int(input())
A = sorted(map(int, input().split()))
L = []
if A[0] >= 0:
  x = A[0]
  for i in range(1, n-1):
    L.append((x, A[i]))
    x -= A[i]
  L.append((A[-1], x))
  M = A[-1] - x
elif A[-1] < 0:
  x = A[-1]
  for i in range(1, n):
    L.append((x, A[n-1-i]))
    x -= A[n-1-i]
  M = x
else:
  for i in range(n):
    if A[i] >= 0:
      border = i
      break
  for i in range(border, n-1):
    L.append((A[0], A[i]))
    A[0] -= A[i]
  x = A[-1]
  for i in range(border):
    L.append((x, A[i]))
    x -= A[i]
  M = x
  
print(M)
for x, y in L:
  print(x, y)

Submission status: Accepted

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

Submission status: Accepted

Solution code:

N = int(input())

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

#%%

A.sort()

keyz = 0
for a in A:
    if a<0:
        keyz += 1

if keyz==0:
    keyz = 1
elif keyz == N:
    keyz = N-1


M = 0
M += -sum(A[:keyz])
M += sum(A[keyz:])
print(M)

# A[0:keyz]までを負とする
    

# A[keyz:]は反転させる必要あり

if keyz == N-1:
    cur = A[-1]
    for i in range(N-1):
        print(cur,A[i])
        cur -= A[i]
    
else:            
    cur = A[0]
    for i in range(keyz,N-1):
        print(cur,A[i])
        cur = cur - A[i]
    print(A[N-1],cur)
    cur = A[N-1] - cur
    for i in range(1,keyz):
        print(cur,A[i])
        cur -= A[i]

Submission status: Accepted

Solution code:
n = int(input())
L = list(map(int,input().split()))
L.sort()
T = []
plus = []
minus = []
for i in range(n):
  if L[i] >= 0:
    plus.append(L[i])
  else:
    minus.append(L[i])
if len(L) == 2:
  if len(plus) == len(minus):
    print(plus[0]-minus[0])
    print(plus[0],minus[0])
  elif len(plus) == 2:
    print(plus[1]-plus[0])
    print(plus[1],plus[0])
  else:
    print(minus[1]-minus[0])
    print(minus[1],minus[0])
else:
  if len(plus) != 0 and len(minus) != 0:
    if min(len(plus),len(minus)) >= 2:
      T.append([minus[0],plus[0]])
      cur = minus[0]-plus[0]
      for i in range(1,len(plus)-1):
        T.append([cur,plus[i]])
        cur = cur-plus[i]
      T.append([plus[len(plus)-1],cur])
      cur = plus[len(plus)-1]-cur
      for i in range(1,len(minus)):
        T.append([cur,minus[i]])
        cur = cur-minus[i]
      print(cur)
      for i in range(len(T)):
        print(T[i][0],T[i][1])
    else:
      if len(minus) == 1:
        cur = minus[0]
        T.append([cur,plus[0]])
        cur = cur-plus[0]
        for i in range(1,len(plus)-1):
          T.append([cur,plus[i]])
          cur = cur-plus[i]
        T.append([plus[len(plus)-1],cur])
        cur = plus[len(plus)-1]-cur
        print(cur)
        for i in range(len(T)):
          print(T[i][0],T[i][1])
      else:
        cur = plus[0]
        T.append([cur,minus[0]])
        cur = cur-minus[0]
        for i in range(1,len(minus)):
          T.append([cur,minus[i]])
          cur = cur-minus[i]
        print(cur)
        for i in range(len(T)):
          print(T[i][0],T[i][1])
  elif len(plus) == 0:
    cur = minus[len(minus)-1]
    for i in range(n-1):
      T.append([cur,minus[n-i-2]])
      cur = cur-minus[n-i-2]
    print(cur)
    for i in range(len(T)):
      print(T[i][0],T[i][1])
  else:
    cur = plus[0]
    for i in range(1,n-1):
      T.append([cur,plus[i]])
      cur = cur-plus[i]
    T.append([plus[n-1],cur])
    cur = plus[n-1]-cur
    print(cur)
    for i in range(len(T)):
      print(T[i][0],T[i][1])

Submission status: Accepted

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

a.sort()

absum=0
minabs=10**9
for num in a:
        abnum=abs(num)
        absum+=abnum
        if minabs > abnum:
                minabs=abnum

if a[0] <= 0 and a[-1] >=0:
        print(absum)
else:
        print(absum - 2*minabs)
        num1=a.pop(0)
        num2=a.pop(-1)
        if abs(num1) > abs(num2):
                print(num2,num1)
                a.append(num2-num1)
        else:
                print(num1,num2)
                a.append(num1-num2)
a.sort()
#print(a)

now = a[0]
for i in range(len(a)-2,-1,-1):
        if a[i] > 0:
                print(now, a[i])
                now-=a[i]
#print(now)
a[0]=now

now = a[-1]

for i in range(len(a)-1):
        if a[i] >0:
                break
        print(now,a[i])
        now-=a[i]

Submission status: Accepted

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

a = sorted(a)

min = a[0]
max = a[n-1]

ans = []

for i in range(1,n-1):
    temp = a[i]
    if(temp < 0):
        ans.append('{} {}'.format(max, temp))
        max -= temp
    else:
        ans.append('{} {}'.format(min, temp))
        min -= temp

ans.append('{} {}'.format(max, min))
max -= min

print(max)

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
plus, minus = [], []
for x in a:
    if x < 0: minus.append(x)
    else: plus.append(x)

if plus and minus:
    print(sum(map(abs, a)))
    p = plus[0]
    for x in minus[1:]:
        print(p, x)
        p -= x
    
    m = minus[0]
    for x in plus[1:]:
        print(m, x)
        m -= x
    
    print(p, m)

if not plus:
    minus.sort(reverse=True)
    m = minus[0]
    print(-(sum(minus) - m * 2))
    for x in minus[1:]:
        print(m, x)
        m -= x

if not minus:
    plus.sort()
    p = plus[0]
    print(sum(plus) - p * 2)
    for x in plus[2:]:
        print(p, x)
        p -= x
    print(plus[1], p)

Submission status: Accepted

Solution code:
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
    return sys.stdin.readline()[:-1]
mod=10**9+7

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

lst=[]

flag=0
for i in range(n-1):
    if a[i+1]>0:
        flag=i+1
        break
if flag==0:
    flag=n-1
tmp=a[0]
for i in range(flag,n-1):
    lst.append([tmp,a[i]])
    tmp-=a[i]
a[0]=tmp
tmp=a[-1]
for i in range(flag):
    lst.append([tmp,a[i]])
    tmp-=a[i]

print(tmp)
for i in range(n-1):
    print(*lst[i])
    
# print(lst)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
xy=[]
for i in range(n-2,0,-1):
  y=a[i]
  if y>0:
    x=a[0]
    a[0]-=y
  else:
    x=a[n-1]
    a[n-1]-=y
  xy.append((x,y))
print(a[n-1]-a[0])
xy.append((a[n-1],a[0]))
print('\n'.join([' '.join(map(str,t)) for t in xy]))

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
l=[a[0]]
r=[a[-1]]
for i in range(1,n-1):
    if a[i]<=0:
        r.append(a[i])
    else:
        l.append(a[i])
r.sort()
l.sort()
if len(r)==1:
    X=r[0]
    p=[]
else:
    p=[[r[-1],r[-2]]]
    for i in range(len(r)-3,-1,-1):
        p.append([p[-1][0]-p[-1][1],r[i]])
    X=p[-1][0]-p[-1][1]
if len(l)==1:
    Y=l[0]
    q=[]
else:
    q=[[l[0],l[1]]]
    for i in range(2,len(l)):
        q.append([q[-1][0]-q[-1][1],l[i]])
    Y=q[-1][0]-q[-1][1]
print(X-Y)
if p and q:
    for i in range(len(p)):
        print(*p[i])
    for i in range(len(q)):
        print(*q[i])
    print(X,Y)
elif p:
    for i in range(len(p)):
        print(*p[i])
    print(X,Y)
elif q:
    for i in range(len(q)):
        print(*q[i])
    print(X,Y)
else:
    print(X,Y)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
A = lr()
A.sort()
# -の合計数は最大N-1、最小N//2
minus = bisect_left(A, 0)
# minusは負の数の個数
m = min(minus, N-1)
if m == 0: m += 1
# mは最終的にマイナスにする数
answer = -sum(A[:m]) + sum(A[m:])
print(answer)
cur = A[0]
for i in range(m, N-1):
    print(cur, A[i])
    cur -= A[i]

A[0] = cur
cur = A[N-1]
for i in range(m):
    print(cur, A[i])
    cur -= A[i]

# 53

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 
def graph():
    n=inp()
    g=[[] for _ in range(n)]
    for i in range(n):
        a = inp()
        a -= 1
        g[i].append(a)
        g[a].append(i)
    return n,g

def main():
    n = inp()
    a = inpl()
    a.sort()
    ans = []
    cnt = 0
    if a[0] >= 0:
        x = a[0]
        for i in range(n-2):
            ans.append((x,a[i+1]))
            x -= a[i+1]
        ans.append((a[n-1],x))
        cnt = a[n-1]-x        
    elif a[n-1] <= 0:
        x = a[n-1]
        for i in range(n-1):
            ans.append((x,a[i]))
            x -= a[i]
        cnt = x
    else:
        for i in range(n):
            if a[i] >= 0:
                x = a[i-1]
                index = i
                break
        for i in range(index+1,n):
            ans.append((x,a[i]))
            x -= a[i]
        a[index-1] = x
        x = a[index]
        for i in range(index):
            ans.append((x,a[i]))
            x -= a[i]
        cnt = x        
    print(cnt)
    for i in range(n-1):
        print(*ans[i])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort()
M = A[0]
X = [A[0]]
pos = N
for i in range(N):
  if A[i] >= 0:
    pos = i
    break
if pos == 0:
  for i in range(1, N - 1):
    M -= A[i]
    X.append(M)
  S = M
  M = A[N-1] - M
  print(M)
  for i in range(N - 2):
    print(X[i], A[i+1])
  print(A[N - 1], S)
elif 1 <= pos <= N - 1:
  M = sum(abs(_) for _ in A)
  print(M)
  L = A[0]
  for j in range(pos, N - 1):
    print(L, A[j])
    L -= A[j]
  R = A[N - 1]
  print(R, L)
  R -= L
  for j in range(1, pos):
    print(R, A[j])
    R -= A[j]
elif pos == N:
  print(A[N-1] - sum(A[i] for i in range(N-1)))
  R = A[N - 1]
  for i in range(N-1):
    print(R, A[i])
    R -= A[i]

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left

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

    a.sort()

    i0 = bisect_left(a, 0)
    # 0以上の値を指す最小のindex
    # [0,i0) : 負
    # [i0,n) : 正

    sum_ = 0
    if i0 == 0:
        # 0以上のみ
        # [-++...+]
        # [S...E]
        # E-(S-1-2-...)
        ret = []
        s = a[0]
        e = a[-1]
        for x in a[1:-1]:
            ret.append((s, x))
            s -= x
        ret.append((e, s))
        e -= s
        sum_ = e

    elif i0 == n:
        # 負のみ
        # [--...-+]
        # [...S]
        # S-1-2-...
        ret = []
        s = a[-1]
        for x in a[:-1]:
            ret.append((s, x))
            s -= x
        sum_ = s

    else:
        # 正負混在
        # [--...-++...+]
        # [Mm...mp...pP]
        # (P-m-m...)-(M-p-p...)
        ret = []
        m = a[0]
        for x in a[i0:-1]:
            ret.append((m, x))
            m -= x

        p = a[-1]
        for x in a[1:i0]:
            ret.append((p, x))
            p -= x

        ret.append((p, m))
        sum_ = p - m

    print(sum_)
    for row in ret:
        print(*row)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

A.sort()
xy=[]
for i in range(N-2,0,-1):
    y=A[i]
    if y>0:
        x=A[0]
        A[0]-=y
    else:
        x=A[N-1]
        A[N-1]-=y
    xy.append((x,y))

print(A[N-1]-A[0])
xy.append((A[N-1],A[0]))
print('\n'.join([' '.join(map(str,t)) for t in xy]))

Submission status: Accepted

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

A.sort()

m = A[0]
M = A[-1]
ans = list()
for a in A[1: -1]:
    if a < 0:
        ans.append((M, a))
        M = M - a
    else:
        ans.append((m, a))
        m = m - a
ans.append((M, m))
print(M - m)
for x, y in ans:
    print(x, y)

Submission status: Accepted

Solution code:
from _collections import deque
from _ast import Num


def parser():
    while 1:
        data = list(input().split(' '))
        for number in data:
            if len(number) > 0:
                yield (number)


input_parser = parser()


def gw():
    global input_parser
    return next(input_parser)


def gi():
    data = gw()
    return int(data)


MOD = int(1e9 + 7)

import numpy
from collections import deque
from math import sqrt
from math import floor
#https://atcoder.jp/contests/arc091/tasks/arc091_b
#D - Remainder Reminder
"""
if has negative

if all positive

"""

N = gi()
A = [0] * N
ans = 0
max_vi = -1
max_v = -1e4 - 1
min_vi = -1
min_v = 1e4 + 1
for i in range(N):
    a = gi()
    A[i] = a
    if (a >= max_v):
        max_vi = i
        max_v = a
    if (a < min_v):
        min_vi = i
        min_v = a
    ans += abs(a)

seq = []
for i in range(N):
    if i == max_vi or i == min_vi:
        continue
    a = A[i]
    if a >= 0:
        seq.append((min_v, a))
        min_v -= a
    else:
        seq.append((max_v, a))
        max_v -= a
print(max_v - min_v)
for p in seq:
    print("%d %d" % (p[0], p[1]))
print(max_v, min_v)

Submission status: Accepted

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

A.sort(reverse=True)
P=[]
M=[]

for i in A:
    if i<0:
        M.append(i)
    else:
        P.append(i)

ans=[]
if len(M)==0:
    if P[0]==0:
        print(0)
        for i in range(N-1):
            print(0,0)
        exit()
    else:
        x=P.pop()
        y=P.pop(0)
        ans.append([x,y])
        M.append(x-y)
if len(P)==0:
    x=M.pop(0)
    y=M.pop()
    ans.append([x,y])
    P.append(x-y)


for i in range(len(P)-1):
    y=P.pop()
    x=M.pop()
    ans.append([x,y])
    M.append(x-y)

for i in range(len(M)):
    y=M.pop()
    x=P.pop()
    ans.append([x,y])
    P.append(x-y)

print(P[0])

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