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:
INF = 10 ** 100


def solve(ns):
    n = len(ns)
    ns.sort(reverse=True)
    pos = ns[:(n + 1) / 2]
    neg = ns[(n + 1) / 2:]

    while len(pos) > 1 and pos[-1] < 0:
        neg.append(pos.pop())

    neg.sort()
    while len(neg) > 1 and neg[-1] > 0:
        pos.append(neg.pop())

    ans = sum(pos) - sum(neg)
    print ans

    #print pos, neg

    res = INF
    while pos and neg:
        if len(pos) >= 2 and len(neg) >= 2:
            a1, a2 = pos.pop(), pos.pop()
            b1, b2 = neg.pop(), neg.pop()

            c1 = a1 - b1
            print a1, b1

            c2 = b2 - a2
            print b2, a2

            pos.append(c1)
            neg.append(c2)
        elif len(pos) == 1 and len(neg) == 1:
            a1 = pos.pop()
            b1 = neg.pop()
            c = a1 - b1
            print a1, b1

            res = c
        elif len(neg) == 1:
            assert pos
            a1 = pos.pop()
            b1 = neg.pop()

            c = b1 - a1
            print b1, a1

            if not pos and not neg:
                res = c
            else:
                neg.append(c)
        elif len(pos) == 1:
            assert neg
            a1 = pos.pop()
            b1 = neg.pop()

            c = a1 - b1
            print a1, b1

            if not pos and not neg:
                res = c
            else:
                pos.append(c)
        else:
            print pos, neg
            assert False
    assert res == ans
    assert not pos
    assert not neg
    return res

#assert solve([1, -1]) == 2
#assert solve([1, -1, -5]) == 7
#assert solve([1, -1, 3, 4]) == 9

n = int(raw_input())
ns = map(int, raw_input().split())
solve(ns)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
ri = lambda: int(input())
#rl = lambda: [int(x) if x.isdecimal() else x for x in input().split()]
#rl = lambda: list(input().split()))
rl = lambda: map(int,input().split())
rr = lambda N: [list(l) for l in zip(*[rl() for _ in range(N)])]
YN = lambda b: print('YES') if b else print('NO')
yn = lambda b: print('Yes') if b else print('No')
OE = lambda x: print('Odd') if x%2 else print('Even')
INF = 10**18
MOD = 10**9+7

N = ri()
A=list(rl())
A.sort()
ans = []
a_min = A[0]
a_max = A[-1]
if a_max <= 0:
    for i in range(1,N-1):
        y = A[i]
        ans.append([a_max,y])
        a_max -= y
    ans.append([a_max,a_min])
elif a_min > 0:
    for i in range(1,N-1):
        y = A[i]
        ans.append([a_min,y])
        a_min -= y
    ans.append([a_max,a_min])
else:
    ind = 0
    for i in range(1,N):
        if A[i] > 0:
            ind = i
            break
    for i in range(1,ind):
        y = A[i]
        ans.append([a_max,y])
        a_max -= y
    for i in range(ind,N-1):
        y = A[i]
        ans.append([a_min,y])
        a_min -= y
    ans.append([a_max,a_min])


print(a_max-a_min)
for x,y in ans:
    print(x,y)

Submission status: Accepted

Solution code:
from itertools import*
from math import*
from collections import*
from heapq import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = float("inf")
mod = 10**9+7
from functools import reduce
import sys
sys.setrecursionlimit(10**7)

N = int(input())
a = list(map(int,input().split()))
a.sort()
minus = -1
for i in range(N):
    if a[i] < 0:
        minus +=1
    else:
        break

q = deque(a)
if max(a) >= 0 and min(a)<0:
    ans = 0
    for i in range(N):
        ans += abs(a[i])
    print(ans)
    for i in range(minus):
        x = q.pop()
        y = q.popleft()
        print(x,y)
        q.append(x-y)
    for i in range(N-minus-2):
        x = q.popleft()
        y = q.pop()
        print(x,y)
        q.appendleft(x-y)
    print(q[1],q[0])
elif max(a)<0:
    print(-sum(a)+2*a[-1])
    for i in range(N-1):
        x = q.pop()
        y = q.popleft()
        print(x,y)
        q.append(x-y)
else:
    print(sum(a)-2*a[0])
    for i in range(N-2):
            x = q.popleft()
            y = q.pop()
            print(x,y)
            q.appendleft(x-y)
    print(q[1],q[0])

Submission status: Accepted

Solution code:
from itertools import accumulate
from bisect import bisect, bisect_left
from functools import reduce
from itertools import accumulate, product
from operator import itemgetter, xor, mul
from math import sqrt
from random import randint, random
from heapq import heappop, heappush

from fractions import gcd
from collections import Counter, deque, defaultdict

import sys
input = sys.stdin.readline
from sys import setrecursionlimit
setrecursionlimit(10**9)

def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())
l = bisect_left(A, 0)
if l == 0:
    ans = []
    for i in range(N-2, 0, -1):
        ans.append("{} {}".format(str(A[0]), str(A[i])))
        A[0] -= A[i]
    ans.append("{} {}".format(str(A[-1]), str(A[0])))
    score = A[-1] - A[0]

elif l == N:
    ans = []
    for i in range(N-1):
        ans.append("{} {}".format(str(A[-1]), str(A[i])))
        A[-1] -= A[i]
    score = A[-1]

else:
    ans = []
    for i in range(l, N-1):
        ans.append("{} {}".format(str(A[0]), str(A[i])))
        A[0] -= A[i]
    for i in range(l):
        ans.append("{} {}".format(str(A[-1]), str(A[i])))
        A[-1] -= A[i]
    score = A[-1]
print(score)
print(*ans, sep="\n")

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

cnt = bisect_left(a, 0)  # 正の開始点==負の個数

if cnt <= 1:
    print(sum(a) - 2 * a[0])
    t = a[0]
    for i in range(1, N - 1):
        print(t, a[i])
        t -= a[i]
    print(a[-1], t)

else:
    # cnt-1個は正最大に連結
    if cnt == N:
        print(sum(map(abs, a)) + 2 * a[-1])
        t = a[-1]
        for i in range(N - 1):
            print(t, a[i])
            t -= a[i]

    else:
        print(sum(map(abs, a)))
        t = a[-1]
        for i in range(cnt - 1):
            print(t, a[i])
            t -= a[i]
        s = a[cnt - 1]
        for i in range(cnt, N - 1):
            print(s, a[i])
            s -= a[i]
        print(t, s)

Submission status: Accepted

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

M = A[-1]
m = A[0]

ans = []
for i, a in enumerate(A[1:-1]):
    if a > 0:
        ans.append([m, a])
        m -= a
    else:
        ans.append([M, a])
        M -= a

print(M - m)
ans.append([M, m])
for a1, a2 in ans:
    print(a1, a2)

Submission status: Accepted

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

x = []
y = []
P = sorted((a for a in A if a >= 0), reverse=True)
Q = sorted(a for a in A if a < 0)
if not Q:
    M = sum(P[:-2]) + (P[-2] - P[-1])
    for _ in range(N - 2):
        X = P.pop()
        Y = P.pop()
        x.append(X)
        y.append(Y)
        P.append(X - Y)
    Y = P.pop()
    X = P.pop()
    x.append(X)
    y.append(Y)
elif not P:
    M = -sum(Q[:-2]) - (Q[-2] - Q[-1])
    for _ in range(N - 1):
        X = Q.pop()
        Y = Q.pop()
        x.append(X)
        y.append(Y)
        Q.append(X - Y)
else:
    M = sum(abs(a) for a in A)
    for _ in range(N - 1):
        if len(P) == 1:
            X = P.pop()
            Y = Q.pop()
            x.append(X)
            y.append(Y)
            P.append(X - Y)
        else:
            X = Q.pop()
            Y = P.pop()
            x.append(X)
            y.append(Y)
            Q.append(X - Y)

print(M)
for X, Y in zip(x, y):
    print('{} {}'.format(X, Y))

Submission status: Accepted

Solution code:
from collections import deque

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

A.sort()
A = deque(A)

B = sum(abs(a) for a in A)

if A[0] * A[-1] <= 0:
    print(B)
    if A[0] == 0:
        for i in range(n - 1, 1, -1):
            print(A[0], A[i])
            A[0] -= A[-1]
            deque.pop(A)
        print(A[1], A[0])
    elif A[-1] == 0:
        for i in range(n - 1):
            print(A[-1], A[i])
            A[-1] -= A[i]

    else:
        L = A.popleft()
        R = A.pop()
        while A:
            if A[-1] >= 0:
                print(L, A[-1])
                L -= A[-1]
            else:
                print(R, A[-1])
                R -= A[-1]
            A.pop()
        print(R, L)

else:
    if A[0] > 0:
        print(B - A[0] * 2)
        for i in range(n - 1, 1, -1):
            print(A[0], A[i])
            A[0] -= A[-1]
            deque.pop(A)
        print(A[1], A[0])
    else:
        print(B + A[-1] * 2)
        while len(A) != 1:
            print(A[-1], A[0])
            A[-1] -= A.popleft()

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))
A.sort()
ans=0
plus,minus=0,0
for a in A:
    if a>=0:
        plus+=1
    elif a<0:
        minus+=1
if plus==0:
    plus=1
    minus=n-1
elif minus==0:
    minus=1
    plus=n-1
Ans=[]
if plus==1:
    Ans.append((A[-1],A[0]))
    tmp=A[-1]-A[0]
    for i in range(1,n-1):
        Ans.append((tmp,A[i]))
        tmp=tmp-A[i]
else:
    Ans.append((A[0],A[minus]))
    tmp=A[0]-A[minus]
    for i in range(minus+1,n-1):
        Ans.append((tmp,A[i]))
        tmp=tmp-A[i]
    Ans.append((A[-1],tmp))
    tmp=A[-1]-tmp
    for i in range(1,minus):
        Ans.append((tmp,A[i]))
        tmp=tmp-A[i]
print(tmp)
for a,b in Ans:
    print(a,b)

Submission status: Accepted

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

A.sort()

M = 0
for i in range(N):
    if i == 0:
        M -= A[i]
    elif i == N-1:
        M += A[i]
    else:
        M += abs(A[i])
print (M)

if N == 2:
    print (A[1], A[0])
    sys.exit()

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

Submission status: Accepted

Solution code:
n = int(input())

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

ps = [p for p in aa if p >= 0]
ns = [p for p in aa if p < 0]

ps = sorted(ps)
ns = sorted(ns)

acts = []
if len(ps) == 0:
  m = ns.pop()
  for nn in ns:
    acts.append((m, nn))
    m -= nn
elif len(ns) == 0:
  m = ps[0]
  for i in range(1, len(ps)-1):
    acts.append((m, ps[i]))
    m -= ps[i]
  acts.append((ps[-1], m))
  m = ps[-1] - m
else:
  m = ns[0]
  for i in range(len(ps)-1):
    acts.append((m, ps[i]))
    m -= ps[i]
  ns[0] = m
  m = ps[-1]
  for i in range(len(ns)):
    acts.append((m, ns[i]))
    m -= ns[i]
  
print(m)
for x, y in acts:
  print(x, y)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, A: "List[int]"):
    A = sorted(A)
    accm = A[0]
    accp = A[-1]
    pas = deque(sorted([a for a in A[1:-1] if 0 <= a], reverse = True))
    mas = deque(sorted([a for a in A[1:-1] if a < 0]))

    result = []
    while 0 < len(pas):
        p = pas.popleft()
        result.append("{} {}".format(accm, p))
        accm -= p
    result.append("{} {}".format(accp, accm))
    accp -= accm

    while 0 < len(mas):
        m = mas.popleft()
        result.append("{} {}".format(accp, m))
        accp -= m
    result = [str(accp)] + result
    return result


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]"
    result = solve(N, A)
    if isinstance(result, Iterable) and not isinstance(result, str):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline

N = int(readline())
A = list(map(int, readline().split()))

A.sort()

amax = A.pop(-1)
amin = A.pop(0)
neg = [a for a in A if a < 0]
pos = [a for a in A if a >= 0]

log = []

m = amin
for a in pos:
    log.append((m, a))
    m = m - a

M = amax
for a in neg:
    log.append((M, a))
    M = M - a

log.append((M, m))
ans = M - m

print(ans)
for l, r in log:
    print('{} {}'.format(l, r))

Submission status: Accepted

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

if N == 2:
    print(max(A)-min(A))
    print('{} {}'.format(max(A),min(A)))
else:
    p = [a for a in A if a>=0]
    n = [a for a in A if a<0]

    ans = []
    if len(n) == 0:
        p.sort()
        x = p.pop(0)
        y = p.pop()
        ans.append('{} {}'.format(x,y))
        n.append(x-y)
    if len(p) == 0:
        n.sort()
        x = n.pop()
        y = n.pop(0)
        ans.append('{} {}'.format(x,y))
        p.append(x-y)

    x = n.pop()
    while len(p)>1:
        y = p.pop()
        ans.append('{} {}'.format(x,y))
        x -= y
    y = x
    x = p[0]
    ans.append('{} {}'.format(x,y))
    x -= y
    while n:
        y = n.pop()
        ans.append('{} {}'.format(x,y))
        x -= y

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

Submission status: Accepted

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

if N == 2:
  A.sort()
  print(A[1] - A[0])
  print(A[1], A[0])
  exit()

p = []
m = []
for i in A:
  if i > 0:
    p.append(i)
  else:
    m.append(i)

p.sort()
m.sort()
ans = [[0, 0]] * (N - 1)
cnt = 0

if len(m) == 0:
  ans[0] = [p[0], p[1]]
  k = p[0] - p[1]
  for i in range(1, N - 2):
    ans[i] = [k, p[i + 1]]
    k -= p[i + 1]
  ans[-1] = [p[-1], k]
  k = p[-1] - k
elif len(p) == 0:
  ans[0] = [m[-1], m[0]]
  k = m[-1] - m[0]
  for i in range(1, N - 1):
    ans[i] = [k, m[i]]
    k -= m[i]
else:
  k = m[0]
  for i in range(len(p) - 1):
    ans[i] = [k, p[i]]
    k -= p[i]
  ans[len(p) - 1] = [p[-1], k]
  k = p[-1] - k
  for i in range(1, len(m)):
    ans[len(p) - 1 + i] = [k, m[i]]
    k -= m[i]

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

Submission status: Accepted

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

steps = []
amin, amax = min(an), max(an)
sum_min, sum_max = amin, amax
flg_min, flg_max = True, True

for a in an:
  if a == amin and flg_min:
    flg_min = False
    continue
  if a == amax and flg_max:
    flg_max = False
    continue
  
  if a >= 0:
    steps.append([sum_min, a])
    sum_min -= a
  else:
    steps.append([sum_max, a])
    sum_max -= a

steps.append([sum_max, sum_min])

print(sum_max - sum_min)
for step in steps:
  print(' '.join(map(str, step)))

Submission status: Accepted

Solution code:
N = int(input())
A = sorted(map(int, input().split()))
mi = A[0]
ma = A[-1]
Ans = []
for i, a in enumerate(A[1:-1], 1):
    if a < 0:
        Ans.append([ma, a])
        ma -= a
    else:
        Ans.append([mi, a])
        mi -= a

print(ma - mi)
for x, y in Ans:
    print(x, y)
print(ma, mi)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def YesNo(x): return 'Yes' if x else 'No'
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 input()
from bisect import bisect

def main():
    N = II()
    A = LI()
    A.sort()
    zero = 1 + bisect(A[1:-1], 0)
    ans = sum(A[zero:]) - sum(A[:zero])
    print(ans)
    x = A[0]
    for i in A[zero:-1]:
        print(x, i)
        x -= i
    y = A[-1]
    print(y, x)
    y -= x
    for i in A[1:zero]:
        print(y, i)
        y -= i
    return

main()

Submission status: Accepted

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

a = [a[len(a)-1]] + a[0:len(a)-1] + [-10000000000000]
li = []

for i in range(n-1):
    if a[i+2] >= 0:
        # 負にしたい
        if a[i+1] > a[i]:
            li.append([a[i], a[i+1]])
            ans = a[i] - a[i+1]
            a[i+1] = a[i] - a[i+1]
        else:
            li.append([a[i+1], a[i]])
            ans = a[i+1] - a[i]
            a[i+1] = a[i+1] - a[i]
    if a[i+2] < 0:
        # 正にしたい
        if a[i+1] > a[i]:
            li.append([a[i+1], a[i]])
            ans = a[i+1] - a[i]
            a[i+1] = a[i+1] - a[i]
        else:
            li.append([a[i], a[i+1]])
            ans = a[i] - a[i+1]
            a[i+1] = a[i] - a[i+1]

print(ans)
for i in li:
    print(' '.join(map(str, i)))

Submission status: Accepted

Solution code:
n = int(input())
l = list(map(int, input().split()))
mi = min(l)
ma = max(l)
l.remove(mi)
l.remove(ma)
u = []
for i in l:
    if i <= 0 :
        u.append([ma,i])
        ma -= i
    else :
        u.append([mi,i])
        mi -= i
u.append([ma,mi])
print(ma-mi)
for i in u:
    print(*i)

Submission status: Accepted

Solution code:
N=int(input())
A=sorted(list(map(int, input().split())))
m=A[0]
M=A[-1]
S=[]
for a in A[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())
A = [int(x) for x in input().split()]
mn = min(A)
mx = max(A)

A.remove(mn)
A.remove(mx)


moves = []
for a in A:
    if a >= 0:
        moves.append((mn, a))
        mn -= a
    else:
        moves.append((mx, a))
        mx -= a

moves.append((mx,mn))
mx -= mn
print(mx)
print('\n'.join(str(a)+' '+str(b) for a,b in moves))

Submission status: Accepted

Solution code:
import numpy as np
# たいてい全部良い符号でとれる
N = int(input())
A = np.array(input().split(),dtype = np.int32)
# インデックス要らないので
A.sort()
A = A[::-1] # desc

positive = (A > 0).sum()
negative = (A <= 0).sum()

A = list(A)
operations = []

if positive == 0:
  # 全部negative
  # 最大値だけプラスでとって、あとは全部引く
  x = A[0]
  for y in A[1:]:
    operations.append((x,y))
    x -= y
  answer = x
elif negative == 0:
  x = A[-1]
  for y in A[1:-1]:
    operations.append((x,y))
    x -= y
  operations.append((A[0],x))
  answer = A[0] - x
else:
  x = A[0] # positive
  y = A[-1] # negative
  for z in A[1:-1]:
    if z > 0:
      operations.append((y,z))
      y -= z
    else:
      operations.append((x,z))
      x -= z
  operations.append((x,y))
  answer = x - y
  
print(answer)
for x,y in operations:
  print(x,y)

Submission status: Accepted

Solution code:
import sys
range = xrange
input = raw_input


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

A.sort()

sign_stack = []
value_stack = [(A[n-1],A[0])]
numb = A[n-1] - A[0]
for i in reversed(range(1,n-1)):
    if A[i] >= 0:
        sign_stack.append(-1)
        numb = -numb
        value_stack.append((A[i], numb))
        numb = A[i] - numb
    else:
        sign_stack.append(1)
        value_stack.append((numb, A[i]))
        numb = numb - A[i]
sign_stack.append(1)

print numb
for sign,(x,y) in zip(sign_stack, value_stack):
    if sign>0:
        print x,y
    else:
        print y,x

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def main():
    # input part
    N = int(input())
    L = LI()
    L.sort()
    m = L[0]
    M = L[N-1]
    ANS = []
    for i in range(1, N-1):
        if L[i] > 0:
            ANS.append((m, L[i]))
            m -= L[i]
            continue
        ANS.append((M, L[i]))
        M -= L[i]
    ANS.append((M, m))
    print(M-m)
    for (x, y) in ANS:
        print(x, y)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
pl = []
mi = []
for x in a:
  if x < 0:
    mi.append(x)
  else:
    pl.append(x)
a = 0
mi.sort()
pl.sort()
move = []
if mi == []:
  cur = pl[0]
  for i in range(n-2):
    move.append((cur,pl[i+1]))
    cur -= pl[i+1]
  move.append((pl[-1],cur))
  cur = pl[-1] - cur
elif pl == []:
  cur = mi[-1]
  for i in range(n-1):
    move.append((cur,mi[i]))
    cur -= mi[i]
else:
  pl1 = pl.pop()
  mi1 = mi.pop()
  for x in mi:
    move.append((pl1,x))
    pl1 -= x
  for y in pl:
    move.append((mi1,y))
    mi1 -= y
  move.append((pl1,mi1))
  cur = pl1-mi1
print(cur)
for x,y in move:
  print(x,y)

Submission status: Accepted

Solution code:
rr = raw_input
rrm = lambda: map(int, rr().split())

from collections import deque
def solve(N, A):
    S = sum(A)
    A.sort()
    A = deque(A)
    moves = []

    if A[0] > 0: # all pos, ans is S - A[0]
        ans = S - A[0]
        x = A.popleft()
        while len(A) >= 2:
            y = A.popleft()
            moves.append([x,y])
            x = x-y
        moves.append([A.pop(), x])
    elif A[-1] < 0:  # all neg, ans is -S + A[-1]
        ans = A[-1] - S
        x = A.pop()
        while A:
            y = A.pop()
            moves.append([x,y])
            x-=y
    else:
        pos = A.pop()
        neg = A.popleft()
        # neg soaks all pos
        while A and A[-1] >= 0:
            x = A.pop()
            moves.append([neg, x])
            neg -= x
        while A and A[0] <= 0:
            x = A.pop()
            moves.append([pos, x])
            pos -= x
        moves.append([pos, neg])
    return moves

N = int(rr())
A = rrm()
moves = solve(N, A)
ans = moves[-1][0] - moves[-1][1]
print ans
for row in moves:
    print " ".join(map(str, row))

Submission status: Accepted

Solution code:
N=int(input())
A=[int(i) for i in input().split()]
if min(A)>=0:
  A.sort()
  print(sum(A)-2*A[0])
  k=A[0]
  for i in range(1,N-1):
    print(k,A[i])
    k-=A[i]
  print(A[N-1],k)
  exit()
if max(A)<=0:
  A.sort()
  print(-sum(A)+2*A[N-1])
  k=A[N-1]
  for i in range(1,N-1)[::-1]:
    print(k,A[i])
    k-=A[i]
  print(k,A[0])
  exit()
A.sort()
A_=list(map(abs,A))
print(sum(A_))
for i in range(1,N-1):
  if A[i]<0:
    print(A[N-1],A[i])
    A[N-1]-=A[i]
  else:
    print(A[0],A[i])
    A[0]-=A[i]
print(A[N-1],A[0])

Submission status: Accepted

Solution code:
n = int(input())
num_list = sorted([ int(v) for v in input().split() ])
ope_list = [ None for i in range(n-1) ]

for i in range(n-2):
    if num_list[i+1] >= 0:
        ope_list[i] = (num_list[0],num_list[i+1])
        num_list[0] -= num_list[i+1]
    else:
        ope_list[i] = (num_list[-1],num_list[i+1])
        num_list[-1] -= num_list[i+1]

ope_list[-1] = (num_list[-1], num_list[0])
ans = num_list[-1] - num_list[0]
print(ans)
for i in range(n-1):
    print(*ope_list[i])

Submission status: Accepted

Solution code:
import bisect


def solve(n, nums):
    nums.sort()
    i = bisect.bisect(nums, 0)
    if i == n:
        i -= 1
    elif i == 0:
        i += 1
    tmp1 = nums[0]
    tmp2 = nums[-1]
    buf = []
    for m in nums[1:i]:
        buf.append('{} {}'.format(tmp2, m))
        tmp2 -= m
    for m in nums[i:-1]:
        buf.append('{} {}'.format(tmp1, m))
        tmp1 -= m
    buf.append('{} {}'.format(tmp2, tmp1))
    print(tmp2 - tmp1)
    print('\n'.join(buf))


n = int(input())
nums = list(map(int, input().split()))
solve(n, nums)

Submission status: Accepted

Solution code:

import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
mii=lambda:map(int,input().split())

n=int(input())

pos=[]
neg=[]
z=0

for i in mii():
    if i>=0: pos.append(i)
    else: neg.append(i)

if not pos:
    x=max(neg)
    neg.remove(x)
    pos.append(x)
if not neg:
    x=min(pos)
    pos.remove(x)
    neg.append(x)

merge=[]
while len(pos)>1:
    merge.append((neg[0],pos[-1]))
    neg[0]-=pos.pop(-1)
while len(neg)>0:
    merge.append((pos[0],neg[-1]))
    pos[0]-=neg.pop(-1)

print(pos[0])
for i,j in merge:
    print("%d %d"%(i,j))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;
using i64 = int64_t;

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N;
    cin >> N;
    vector<int> A(N);
    for(auto&& x:A)cin >> x;
    sort(A.begin(), A.end());
    int sum = 0;
    for(int i=1;i<N-1;i++)sum += abs(A[i]);
    cout << A[N-1] + sum - A[0] << endl;
    for(int i=1;i<N-1;i++){
        if(A[i] < 0){
            cout << A[N-1] << " " << A[i] << endl;
            A[N-1] -= A[i];
        }else{
            cout << A[0] << " " << A[i] << endl;
            A[0] -= A[i];
        }
    }
    cout << A[N-1] << " " << A[0] << endl;
    return 0;
}

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque
import sys
#input = sys.stdin.readline
def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())

print(a[-1] - sum(map(abs, A[1:-1])) - A[0])
for i in range(N-2, 0, -1):
	a = A[i]
	if a > 0:
    	print(A[0], a)
    	A[0] -= a
    else:
    	print(A[-1], a)
    	A[-1] -= a
    	print(A[-1], A[0])

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque
import sys
#input = sys.stdin.readline
def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())

print(a[-1] - sum(map(abs, A[1:-1])) - A[0])
for i in range(N-2, 0, -1):
  a = A[i]
  if a > 0:
    print(A[0], a)
    A[0] -= a
    else:
      print(A[-1], a)
      A[-1] -= a
      print(A[-1], A[0])

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque
import sys
#input = sys.stdin.readline
def inpl(): return list(map(int, input().split()))
N = int(input())
A = sorted(inpl())

print(sum(map(abs, A[1:])) - A[0])
for i in range(N-2, 0, -1):
  a = A[i]
  if a > 0:
    print(A[0], a)
    A[0] -= a
    else:
      print(A[-1], a)
      A[-1] -= a
      print(A[-1], A[0])

Submission status: Runtime Error

Solution code:
N=int(input())
L=list(map(int,input().split()))
L=sorted(L)
ans=[]
for i in range(N-2):
  ans.append(L[0])
  ans.append(L[1])
  s=L[0]-L[1]
  L.append(s)
  L=L[2:]
  L=sorted(L)
  if len(L)==2:
    ans.append(max(L))
    ans.append(min(L))
s=ans[-2]-ans[-1]
print(s)
for i in range(0,len(ans),2):
  print(f"{ans[i]} {ans[i+1]}")

Submission status: Runtime Error

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    H, W = LI()
    A = [SS() for _ in range(H)]

    d = ((1, 0), (0, 1), (-1, 0), (0, -1))

    dist = [[INF] * W for i in range(H)]
    que = collections.deque()

    for i, j in itertools.product(range(H), range(W)):
        if A[i][j] == '#':
            que.append((i, j))
            dist[i][j] = 0

    while que:
        cy, cx = que.popleft()
        for dy, dx in d:
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and dist[cy][cx] + 1 < dist[ny][nx]:
                dist[ny][nx] = dist[cy][cx] + 1
                que.append((ny, nx))

    # for i in dist:
    #     print(i)

    ans = max([max(i) for i in dist])
    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
from bisect import bisect

def solve():
    N = int(input())
    A = sorted(map(int,input().split()))
    if N == 2:
        res = [(max(A),min(A))]
        s = max(A)-min(A)
        return s, res

    if A[0] >= 0:
        res = []
        x = A[0]
        for a in A[1:-1]:
            res.append((x,a))
            x -= a
        res.append((A[-1],x))
        x = A[-1]-x
        return (x,res)
    if A[-1] <= 0:
        res = []
        x = A[-1]
        for a in A[-1]:
            res.append((x,a))
            x -= a
        return (x,res)

    res = []
    p = bisect(A,0)-1
    x = A[p]
    for a in A[p+1:N-1]:
        res.append((x,a))
        x -= a
    res.append((A[-1],x))
    x = A[-1]-x
    for a in A[:p]:
        res.append((x,a))
        x -= a
    return (x,res)



s,res = solve()
print(s)
print('\n'.join(f'{a} {b}' for a,b in res))

Submission status: Runtime Error

Solution code:
from bisect import bisect

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


    if A[0] >= 0:
        res = []
        x = A[0]
        for a in A[1:-1]:
            res.append((x,a))
            x -= a
        res.append((A[-1],x))
        x = A[-1]-x
        return (x,res)
    if A[-1] <= 0:
        res = []
        x = A[-1]
        for a in A[-1]:
            res.append((x,a))
            x -= a
        return (x,res)

    res = []
    p = bisect(A,0)-1
    x = A[p]
    for a in A[p+1:N-1]:
        res.append((x,a))
        x -= a
    res.append((A[-1],x))
    x = A[-1]-x
    for a in A[:p]:
        res.append((x,a))
        x -= a
    return (x,res)



s,res = solve()
print(s)
print('\n'.join(f'{a} {b}' for a,b in res))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#define Int int64_t

using namespace std;

int main() {
	int N;
	cin >> N;
	vector<int> A(N);
	for (int i = 0; i < N; ++i) { cin >> A[i]; }

	sort(A.begin(), A.end());
	vector<pair<int, int>> xy;
	for (int i = 1; i < N - 1; ++i) {
		if (A[i] > 0) {
			xy.emplace_back( A[0], A[i] );
			A[0] -= A[i];
		} else {
			xy.emplace_back( A.back(), A[i] );
			A.back() -= A[i];
		}
	}
	cout << A.back() - A[0] << "\n";
	for (auto p : xy) {
		cout << p.first << " " << p.second << "\n";
	}
	cout << A.back() << " " << A[0] << "\n";

	return 0;
}

Submission status: Runtime Error

Solution code:
import sys,math,collections,itertools,bisect
input = sys.stdin.readline

N=int(input())
A=list(map(int,input().split()))
process = []
#--最大最小を見つける--#
maxA = A.pop(A.index(max(A)))
minA = A.pop(A.index(min(A)))
A.append(minA-maxA)
process.append(A)

for i in range(len(A)-2):
    maxA = A.pop(A.index(max(A)))
    A[-1]-=maxA
    process.append(list(q))
print(A[0]-A[-1])
for pro in process:
    print(*pro)