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:
from sys import stdin

if __name__ == '__main__':
    N = int(stdin.readline())
    A = [int(x) for x in stdin.readline().rstrip().split()]

    A.sort(reverse=True)
    A_max = A.pop(0)

    A_minus = [i for i in A if i < 0]
    A_plus = [j for j in A if j >= 0]

    if len(A_minus) > 0:
        print(A_max - sum(A_minus) + sum(A_plus))

        A_minus.sort(reverse=False)
        tmp = A_minus.pop(0)

        for j in range(len(A_plus)):
            print(str(tmp) + " " + str(A_plus[j]))
            tmp = tmp - A_plus[j]

        print(str(A_max) + " " + str(tmp))
        tmp = A_max - tmp

        for i in range(len(A_minus)):
            print(str(tmp) + " " + str(A_minus[i]))
            tmp = tmp - A_minus[i]

    else:
        A_plus.sort(reverse=False)
        tmp = A_plus.pop(0)
        print(A_max - tmp + sum(A_plus))
        for i in range(len(A_plus)):
            print(str(tmp) + " " + str(A_plus[i]))
            tmp = tmp - A_plus[i]

        print(str(A_max) + ' ' + str(tmp))

Submission status: Accepted

Solution code:
n=int(input())
a_list=list(map(int,input().split()))
a_list.sort()
import bisect
x=bisect.bisect_left(a_list,0)
y=bisect.bisect_right(a_list,0)
neg=a_list[:x]
pos=a_list[y:]
zero=y-x
if zero==n:
    print(0)
    for i in range(n-1):
        print(0,0)
else:
    if neg==[]:
        if zero==0:
            m=sum(pos[1:])-pos[0]
            print(m)
            now=pos[0]
            for i in pos[1:-1]:
                print(now,i)
                now=now-i
            print(pos[-1],now)
        else:
            m=sum(pos)
            print(m)
            for i in range(zero-1):
                print(0,0)
            now=0
            for i in pos[:-1]:
                print(now,i)
                now=now-i
            print(pos[-1],now)
    elif pos==[]:
        if zero==0:
            m=abs(sum(neg[:-1])-neg[-1])
            print(m)
            now=neg[-1]
            for i in neg[:-1]:
                print(now,i)
                now=now-i
        else:
            m=abs(sum(neg))
            print(m)
            for i in range(zero-1):
                print(0,0)
            now=0
            for i in neg:
                print(now,i)
                now=now-i
    else:
        if zero==0:
            m=-sum(neg)+sum(pos)
            print(m)
            now=neg[0]
            for i in pos[1:]:
                print(now,i)
                now=now-i
            print(pos[0],now)
            now=pos[0]-now
            for i in neg[1:]:
                print(now,i)
                now=now-i
        else:
            m=-sum(neg)+sum(pos)
            print(m)
            for i in range(zero-1):
                print(0,0)
            now=neg[0]
            for i in pos:
                print(now,i)
                now=now-i
            print(0,now)
            now=-now
            for i in neg[1:]:
                print(now,i)
                now=now-i

Submission status: Accepted

Solution code:
from collections import deque
N=int(input())
A=list(map(int,input().split()))
A.sort()
A=deque(A)
L=deque([])
for i in range(N):
    if len(A)>=3:
        a=A.popleft()
        b=A.pop()
        if (b-a)-A[0] >= A[-1]-(a-b):
            A.append(b-a)
            L.append([b,a])
        else:
            A.appendleft(a-b)
            L.append([a,b])
    elif len(A)==2:
        a = A.popleft()
        b = A.pop()
        A.append(b-a)
        L.append([b,a])
        break
    else:
        break
print(A[0])
for j in L:
    print(j[0],j[1],sep=' ')

Submission status: Accepted

Solution code:
def main():
    num = int(input())
    data = list(map(int, input().split()))
    data.sort()

    if data[0] <= 0 and data[num - 1] >= 0:
        now_sei = data[num - 1]
        now_fu = data[0]

        ans = 0
        for i in range(num):
            ans += abs(data[i])
        print(ans)

        for i in range(1, num - 1):
            if data[i] > 0:
                print(now_fu, data[i])
                now_fu -= data[i]
            else:
                print(now_sei, data[i])
                now_sei -= data[i]
        print(now_sei, now_fu)

    elif data[num - 1] < 0:
        ans = data[-1]
        for i in range(num - 1):
            ans += abs(data[i])
        print(ans)

        now_moji = data[-1]
        for i in range(num - 1):
            print(now_moji,  data[i])
            now_moji -= data[i]

    elif data[0] > 0:
        ans = -1 * data[0]
        for i in range(1, num):
            ans += abs(data[i])
        print(ans)

        now_moji = data[0]
        for i in range(1, num - 1):
            print(now_moji,  data[i])
            now_moji -= data[i]
        print(data[num - 1], now_moji)






if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import itertools
import collections
sys.setrecursionlimit(10**7)
def lmi(): return list(map(int, input().split()))

n = int(input())
a = lmi()
a.sort()
# print(a)
ans = sum([abs(i) for i in a[1:]]) - a[0]
for i in range(n):
    if a[i] >= 0:
        b = a[:i]
        c = a[i:]
        break
else:
    b = a[:]
    c = []

# print(b,c)

if b == []:
    l = c[0]
    c.pop(0)
else:
    l = b[0]
if c == []:
    # print('%')
    r = b[-1]
    b.pop(-1)
    ans = sum([abs(i) for i in a[:-1]]) + a[-1]
else:
    r = c[-1]

print(ans)
# print('#',l,r)

for i in range(len(c)-1):
    print(l,c[i])
    l -= c[i]
for i in range(len(b)-1):
    print(r,b[-i-1])
    r -= b[-i-1]
print(r, l)

Submission status: Accepted

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

def printAns(array1,array2=[]):
    curr1 = array1[0]
    for i in range(1, len(array1)):
        print(curr1, array1[i])
        curr1 -= array1[i]

    if len(array2)>0:
        curr2 = array2[0]
        for i in range(1, len(array2)):
            print(curr2, array2[i])
            curr2 -= array2[i]
            
        print(curr1, curr2)
        curr1 -= curr2
        
    return curr1

plus = []
minus = []
zero = []
for it in a:
    if it == 0:
        zero.append(it)
    elif it > 0:
        plus.append(it)
    else:
        minus.append(it)

# solve problem
if len(plus) == 0:
    minus += zero
    minus.sort(key=lambda x:abs(x))
    max_value = abs(sum(minus[1:]))-abs(minus[0])
    print(max_value)
    printAns(minus)
elif len(minus) == 0:
    plus += zero
    plus.sort(key=lambda x:abs(x))  
    max_value = sum(plus[1:])-plus[0]
    print(max_value)
    printAns([plus[-1]], plus[:-1])
else:
    plus += zero
    array1 = [plus.pop()]
    array2 = []
    for i, it in enumerate(minus):
        if i==0:
            array2.append(it)
        else:
            array1.append(it)
    # plus
    array2+=plus
    
    max_value = sum(map(abs, a))
    print(max_value)
    tmp = printAns(array1, array2)

Submission status: Accepted

Solution code:
n = int(input())
a = sorted(map(int, input().split()), reverse=True)
x, y = a[0], a[-1]
v = []
for i in a[1:-1]:
    if i > 0:
        v.append((y, i))
        y -= i
    else:
        v.append((x, i))
        x -= i
v.append((x, y))
print(x - y)
for i in v:
    print(i[0], i[1])

Submission status: Accepted

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

L=max(A)
S=min(A)
A.remove(L)
A.remove(S)
for x in A:
    if x>0:
        log += "\n"+str(S)+" "+str(x)
        S = S-x
    else:
        log += "\n"+str(L)+" "+str(x)
        L = L-x
log += "\n"+str(L)+" "+str(S)
L = L-S
print(str(L)+log)

Submission status: Accepted

Solution code:
# n = int(input())
# lists = []
# for i in range(n):
#     lists.append(list(map(int,input().split())))
# print(lists)
# lists.sort()
# print(lists)
n = int(input())
lists = list(map(int,input().split()))
lists.sort()
plus = []
minus = []
total = 0
for a in lists:
    if a < 0:
        minus.append(a)
    else:
        plus.append(a)
mini = min(len(minus), len(plus))
flag = (mini == len(plus))              #プラスのほうが少ないとき
eq_flag = (len(plus) == len(minus))     #プラスの数とマイナスの数が同じだったとき
zero_flag = (mini == 0)                 #符号が偏ってたとき
minus.reverse()


sum_list = 0

total = 0
if len(minus) == 0:
    print(sum(plus)-plus[0]*2)
    total = plus[0]
    for i in range(1,len(plus)-1):
        print(total, plus[i])
        total = total - plus[i]
    print(plus[-1], total)
elif len(plus) == 0:
    print(abs(sum(minus))-abs(minus[0]*2))
    total = minus[0]
    for i in range(1,len(minus)-1):
        print(total, minus[i])
        total = total - minus[i]
    print(total, minus[-1])
else:
    print(abs(sum(plus))+abs(sum(minus)))
    total = minus[-1]
    for i in range(len(plus)-1):
        print(total, plus[i])
        total = total - plus[i]
    print(plus[-1], total)
    total = plus[-1] - total
    for i in range(len(minus)-1):
        print(total, minus[i])
        total = total - minus[i]

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())

pos = deque()
neg = deque()
zeros = 0

for a in map(int, input().split()):
    if a == 0:
        zeros += 1
    else:
        if a > 0:
            pos.append(a)
        else:
            neg.append(a)

for _ in range(zeros):
    if len(pos) == 0:
        pos.append(0)
    else:
        neg.append(0)

pos = sorted(pos)
neg = sorted(neg)
ops = deque()


if len(pos) > 0:
    p0 = pos.pop()
else:
    p0 = neg.pop()

if len(neg) > 0:
    n0 = neg.pop()
else:
    n0 = pos.pop(0)

plast = p0
for n in neg:
    ops.append((plast, n))
    plast = plast - n

nlast = n0
for p in pos:
    ops.append((nlast, p))
    nlast = nlast - p

ops.append((plast, nlast))
m = plast - nlast

print(m)
for x, y in ops:
    print(str(x) + " " + str(y))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

import random
import collections
import math
import itertools

def real_main():
    N = read_int()
    nums = read_int_array()
    x, actions = solve(N, nums)
    print(x)
    for a, b in actions:
        print(a, b)


def solve1(n, nums):
    next_small = n // 2 - 1
    next_big = next_small + 1
    next_op = n % 2

    actions = []
    if next_op:
        last = nums[next_small] - nums[next_big]
        actions.append((nums[next_small], nums[next_big]))
    else:
        last = nums[next_big] - nums[next_small]
        actions.append((nums[next_big], nums[next_small]))

    next_big += 1
    next_small -= 1

    next_op = 1 - next_op
    while next_small >= 0 or next_big < n:
        if next_op:
            actions.append((nums[next_small], last))
            last = nums[next_small] - last
            next_small -= 1
        else:
            actions.append((nums[next_big], last))
            last = nums[next_big] - last
            next_big += 1
        next_op = 1 - next_op

    return last, actions

def solve2(n, nums):
    next_small = (n+1) // 2 - 1
    next_big = next_small + 1
    next_op = n % 2

    actions = []
    if next_op: # maximize
        last = nums[next_big] - nums[next_small]
        #actions.append((nums[next_small], nums[next_big]))
    else: # minimize
        last = nums[next_small] - nums[next_big]
        #actions.append((nums[next_big], nums[next_small]))

    next_big += 1
    next_small -= 1

    next_op = 1 - next_op
    while next_small >= 0 or next_big < n:
        if next_op:
            actions.append((nums[next_big], last))
            last = last - nums[next_big]
            next_big += 1
        else:
            actions.append((nums[next_small], last))
            last = last - nums[next_small]
            next_small -= 1
        next_op = 1 - next_op

    return last, actions

def solve(n, nums):
    nums.sort()
    actions = []
    if nums[0] <= 0 <= nums[-1]:
        ans = nums[0]
        ans2 = nums[-1]
        for i in range(1, n-1):
            if nums[i] > 0:
                actions.append((ans, nums[i]))
                ans -= nums[i]
            else:
                actions.append((ans2, nums[i]))
                ans2 -= nums[i]
        actions.append((ans2, ans))
        ans = ans2 - ans
    elif nums[-1] < 0:
        ans = nums[-1]
        for i in range(n-1):
            actions.append((ans, nums[i]))
            ans -= nums[i]
    else:
        ans = nums[0]
        for i in range(1, n-1):
            actions.append((ans, nums[i]))
            ans -= nums[i]
        actions.append((nums[-1], ans))
        ans = nums[-1] - ans
    return ans, actions


def solveSlow(n, nums):

    def maximize(nums):
        if len(nums) == 2:
            return max(nums[0] - nums[1], nums[1] - nums[0])
        nums.sort()
        return max(nums[-1] - minimize(nums[:-1]), maximize(nums[1:]) - nums[0])

    def minimize(nums):
        if len(nums) == 2:
            return min(nums[0] - nums[1], nums[1] - nums[0])
        nums.sort()
        return min(minimize(nums[:-1]) - nums[-1], nums[0] - maximize(nums[1:]))

    return maximize(nums)


def main():
    if 'PYCHARM_HOSTED' in os.environ:
        main_pycharm()
    else:
        real_main()


def generate_nums(n, min, max, check_if_good=None):
    while True:
        nums = [random.randint(min, max) for _ in range(n)]
        if check_if_good is None or check_if_good(nums):
            return nums


from copy import deepcopy
def main_pycharm():
    solution = solve

    test_inputs = []
    for _ in range(100):
        n = random.randint(2, 10)
        test_inputs.append([n, generate_nums(n, -100, 100)])
        test_inputs[-1][1].sort()


    test_outputs = None
    judge = None
    slow_solution = solveSlow
    if solution is not None:
        if test_outputs is not None:
            test_with_answers(solution, test_inputs, test_outputs)
        if judge is not None:
            test_with_judge(solution, test_inputs, judge)
        if slow_solution is not None:
            test_with_slow_solution(solution, test_inputs, slow_solution)


def test_with_answers(solution, inputs_answers):
    total, wrong = 0, 0
    for args, test_ans in inputs_answers:
        ans = solution(*args.copy())
        if ans != test_ans:
            print('WRONG! ans=%s, test_ans=%s, args=%s' % (ans, test_ans, args))
            wrong += 1
        else:
            print('GOOD')
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))


def test_with_judge(solution, inputs_gen, judge):
    total, wrong = 0, 0
    for args in inputs_gen:
        ans = solution(*deepcopy(args))
        if not judge(deepcopy(ans), *deepcopy(args)):
            print('WRONG! ans=%s, args=%s' % (ans, args))
            wrong += 1
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))


def test_with_slow_solution(solution, inputs_gen, solution_slow):
    total, wrong = 0, 0
    for args in inputs_gen:
        ans = solution(*deepcopy(args))[0]
        slow = solution_slow(*deepcopy(args))
        if ans != slow:
            print('WRONG! ans=%s, slow=%s, args=%s' % (ans, slow, args))
            wrong += 1
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

read = input
read_int = lambda: int(input())
read_array = lambda sep=None, maxsplit=-1: input().split(sep, maxsplit)
read_int_array = lambda: [int(a) for a in read_array()]

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

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

l.sort()

if l[0] >= 0:
    #all +
    m = sum(l[1:])-l[0]
    print(m)
    curr = l[0]
    for i in range(n-2):
        print(curr,l[i+1])
        curr -= l[i+1]
    print(l[-1],curr)
elif l[-1]<=0:
    m = l[-1] - sum(l[:-1])
    print(m)
    curr = l[-1]
    for i in range(n-1):
        print(curr,l[n-2-i])
        curr -= l[n-2-i]
else:
    m = sum([abs(item) for item in l])
    print(m)
    idx = 0
    for i in range(n):
        if l[i]>=0:
            idx=i
            break
    plus = l[idx:]
    minus = l[:idx]
    curr = minus[0] 
    for i in range(len(plus)-1):
        print(curr,plus[i])
        curr -= plus[i]
    print(plus[-1],curr)
    curr = plus[-1] - curr
    for i in range(len(minus)-1):
        print(curr,minus[i+1])
        curr -= minus[i+1]

Submission status: Accepted

Solution code:
import sys
from collections import deque

def main():
    input = sys.stdin.readline
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()

    q = deque()
    q.extend(A)
    M = q.pop()
    x = q.popleft()
    operation = []
    while len(q) > 0:
        y = q.pop()
        if y < 0:
            operation.append((M, y))
            M -= y
        else:
            operation.append((x, y))
            x -= y

    operation.append((M, x))
    M -= x

    print(M)
    for x, y in operation:
        print('{} {}'.format(x, y))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
from collections import deque

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N=INT()
A=deque(sorted(LIST()))

ans=[]
while len(A)>=3:
    if A[0]<=0 and A[-1]>=0:
        if A[1]<=0:
            y=A.popleft()
            x=A.pop()
            ans.append((x, y))
            A.append(x-y)
        elif A[-2]>=0:
            x=A.popleft()
            y=A.pop()
            ans.append((x, y))
            A.appendleft(x-y)
        else:
            if A[0]>0:
                x=A.popleft()
                y=A.pop()
                ans.append((x, y))
                A.appendleft(x-y)
            elif A[-1]<0:       
                y=A.popleft()
                x=A.pop()
                ans.append((x, y))
                A.append(x-y)
            else:
                raise Exception
    else:
        if A[0]>0:
            x=A.popleft()
            y=A.pop()
            ans.append((x, y))
            A.appendleft(x-y)
        elif A[-1]<0:       
            y=A.popleft()
            x=A.pop()
            ans.append((x, y))
            A.append(x-y)
        else:
            raise Exception
ans.append((A[-1], A[0]))
print(A[-1]-A[0])
for x, y in ans:
    print(x, y)

Submission status: Accepted

Solution code:
from bisect import bisect

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

ind = bisect(A,0)

X = A[:ind]
Y = A[ind:]
ans = []
if len(X) == 0 :
    ans.append([Y[0],Y[1]])
    X.append(Y[0]-Y[1])
    Y.pop(0)
    Y.pop(0)

if len(Y) == 0 :
    if len(X) != 1 :
        ans.append([X[-1],X[-2]])
        Y.append(X[-1]-X[-2])
        X.pop(-1)
        X.pop(-1)

if len(X) + len(Y) <= 1 :
    if len(X) == 0 :
        calc = Y[0]
    else :
        calc = X[0]

while len(X) + len(Y) >= 2 :
    if len(X) >= 2 :
        if len(Y) != 1 :
            ans.append([X[-1],Y[0]])
            X[-1] -= Y.pop(0)
        else :
            ans.append([Y[0],X[-1]])
            Y[0] -= X.pop(-1)
    elif len(Y) >= 2 :
        if len(X) != 1 :
            ans.append([Y[0],X[-1]])
            Y[0] -= X.pop(-1)
        else :
            ans.append([X[-1],Y[0]])
            X[-1] -= Y.pop(0)
    else :
        calc = Y[0]-X[0]
        ans.append([Y.pop(0),X.pop(0)])

print(calc)
#print(*ans,sep="\n")
for l in ans :
    print(*l)

Submission status: Accepted

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

li.sort()
result1=li[len(li)-1]
result2=li[0]
re=[]
for i in range(1,len(li)-1):
  if li[i]<0:
    re.append([result1,li[i]])
    result1=result1-li[i]
  else:
    re.append([result2,li[i]])
    result2=result2-li[i]
               
re.append([result1,result2])
result1-=result2

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

Submission status: Accepted

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

a.sort()
if a[0] >= 0:
    minus = [a[0]]
    plus = a[1:n]
elif a[n-1] <= 0:
    minus = a[0:n-1]
    plus = [a[n-1]]
else:
    for i in range(n):
        if a[i] > 0:
            point = i
            break
    minus = a[0:point]
    plus = a[point:n]
print(sum(plus)-sum(minus))
for i in range(n-1):
    mi = minus.pop(0)
    pl = plus.pop(0)
    if len(minus) >= len(plus):
        print(str(pl) +' '+str(mi))
        plus.append(pl-mi)
    else:
        minus.append(mi-pl)
        print(str(mi) +' '+str(pl))

Submission status: Accepted

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

A_lis.sort()

N_neg = 0
for j in A_lis:
  if j < 0:
    N_neg += 1
  else:
    break
    
N_pos = len(A_lis) - N_neg

seq = []

neg = A_lis[0]
pos = A_lis[-1]

if N_neg == 0:
  for j in range(N_pos-2):
    ind = j + 1
    seq.append((neg, A_lis[ind]))
    neg = neg - A_lis[ind]
  seq.append((pos, neg))
  print(pos-neg)
  for j in seq:
    print("%d %d" % j)
  exit()
  
if N_pos == 0:
  for j in range(N_neg-1):
    ind = j
    seq.append((pos, A_lis[ind]))
    pos = pos - A_lis[ind]
  print(pos)
  for j in seq:
    print("%d %d" % j)
  exit()
    
for j in range(N_pos-1):
  ind = N_neg + j
  seq.append((neg, A_lis[ind]))
  neg = neg - A_lis[ind]

  
for j in range(N_neg-1):
  ind = j + 1
  seq.append((pos, A_lis[ind]))
  pos = pos - A_lis[ind]
  
seq.append((pos, neg))
print(pos-neg)

for j in seq:
  print("%d %d" % j)

Submission status: Accepted

Solution code:
import heapq
n=int(input())
a=list(map(int,input().split()))
heapq.heapify(a)
stack=[]
p=[]
neg=[]
for i in range(n):
    if(a[i]<0):
        neg.append(a[i])
    else:
        p.append(a[i])
heapq.heapify(neg)
heapq.heapify(p)
for i in range(n-1):
    if neg!=[]:
        if len(p)>1:
            b=heapq.heappop(p)
            c=heapq.heappop(neg)
            stack.append([c,b])
            heapq.heappush(neg,c-b)
        elif len(p)==1:
            b=heapq.heappop(p)
            c=heapq.heappop(neg)
            stack.append([b,c])
            heapq.heappush(p,b-c)
        else:
            neg.sort(reverse=True)
            b=neg.pop(0)
            c=neg.pop(-1)
            stack.append([b,c])
            heapq.heappush(p,b-c)
            heapq.heapify(neg)
    else:
        if len(p)>2:
            b=heapq.heappop(p)
            c=heapq.heappop(p)
            stack.append([b,c])
            heapq.heappush(neg,b-c)
        else:
            b=heapq.heappop(p)
            c=heapq.heappop(p)
            stack.append([c,b])
            heapq.heappush(p,c-b)
if p!=[]:
    print(p[0])
else:
    print(neg[0])
for i in range(n-1):
    print(stack[i][0],stack[i][1])

Submission status: Accepted

Solution code:
N=int(input())
li=list(map(int,input().split()))
plus=[] 
minus=[]
for i in range(0,N):
  if li[i]>0:
    plus.append(li[i])
  else:
    minus.append(li[i])
    
plus.sort()
minus.sort()
#print(plus)
if len(minus)==0:
  M=sum(plus)-2*plus[0]
  print(M)
  a=plus[0]-plus[1]
  aa=0
  print(plus[0],plus[1])
  for i in range(0,N-3):
    aa=a
    a=-plus[i+2]+a
    print(aa,plus[i+2])
  print(plus[N-1],a)
    
    
    
  
elif len(plus)==0:
  M=-sum(minus)+2*minus[len(minus)-1]
  print(M)
  aa=0
  a=minus[N-1]-minus[N-2]
  print(minus[N-1],minus[N-2])
  for i in range(0,N-2):
    aa=a
    a=-minus[N-i-3]+a
    print(aa,minus[N-i-3])
    
  
  
elif len(plus) ==0:
  M=sum(plus)-sum(minus)
  print(M)
  for i in range(0,len(minus)):
    aa=a
    a=aa-minus[i]
    print(aa,minus[i])
  
  
  
elif len(plus)!=1:
  M=sum(plus)-sum(minus)
  print(M)
  aa=0
  a=minus[0]-plus[0]
  print(minus[0],plus[0])
  for i in range(0,len(plus)-2):
    if len(plus)-2==0: break
    aa=a
    a=a-plus[i+1]
    print(aa,plus[i+1])
  aa=a
  a=-a+plus[len(plus)-1]
  print(plus[len(plus)-1],aa)
    
  for j in range(0,len(minus)-1):
    if len(minus)-1==0: break
    aa=a
    a=a-minus[j+1]
    print(aa,minus[j+1])
    
else:
  M=sum(plus)-sum(minus)
  print(M)
  a=plus[0]-minus[0]
  aa=0
  print(plus[0],minus[0])
  for i in range(0,len(minus)-1):
    aa=a
    a=aa-minus[i+1]
    print(aa,minus[i+1])

Submission status: Accepted

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

amin=A[0]
amax=A[-1]
for a in A[1:N-1]:
	if a<0:
		M-=a
	else:
		M+=a
print(M-amin+amax)
for a in A[1:N-1]:
	if a<0:
		print(amax,a)
		amax=amax-a
	else:
		print(amin,a)
		amin=amin-a
print(amax,amin)