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: Wrong Answer

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

import os
import sys
from __builtin__ import xrange as range
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

import random


class TreapMultiSet(object):
    root = 0
    size = 0

    def __init__(self, data=None):
        if data:
            data = sorted(data)
            self.root = treap_builder(data)
            self.size = len(data)

    def add(self, key):
        self.root = treap_insert(self.root, key)
        self.size += 1

    def remove(self, key):
        self.root = treap_erase(self.root, key)
        self.size -= 1

    def discard(self, key):
        try:
            self.remove(key)
        except KeyError:
            pass

    def ceiling(self, key):
        x = treap_ceiling(self.root, key)
        return treap_keys[x] if x else None

    def higher(self, key):
        x = treap_higher(self.root, key)
        return treap_keys[x] if x else None

    def floor(self, key):
        x = treap_floor(self.root, key)
        return treap_keys[x] if x else None

    def lower(self, key):
        x = treap_lower(self.root, key)
        return treap_keys[x] if x else None

    def max(self):
        return treap_keys[treap_max(self.root)]

    def min(self):
        return treap_keys[treap_min(self.root)]

    def __len__(self):
        return self.size

    def __nonzero__(self):
        return bool(self.root)

    __bool__ = __nonzero__

    def __contains__(self, key):
        return self.floor(key) == key

    def __repr__(self):
        return 'TreapMultiSet({})'.format(list(self))

    def __iter__(self):
        if not self.root:
            return iter([])
        out = []
        stack = [self.root]
        while stack:
            node = stack.pop()
            if node > 0:
                if right_child[node]:
                    stack.append(right_child[node])
                stack.append(~node)
                if left_child[node]:
                    stack.append(left_child[node])
            else:
                out.append(treap_keys[~node])
        return iter(out)


class TreapSet(TreapMultiSet):
    def add(self, key):
        self.root, duplicate = treap_insert_unique(self.root, key)
        if not duplicate:
            self.size += 1

    def __repr__(self):
        return 'TreapSet({})'.format(list(self))


class TreapHashSet(TreapMultiSet):
    def __init__(self, data=None):
        if data:
            self.keys = set(data)
            super(TreapHashSet, self).__init__(self.keys)
        else:
            self.keys = set()

    def add(self, key):
        if key not in self.keys:
            self.keys.add(key)
            super(TreapHashSet, self).add(key)

    def remove(self, key):
        self.keys.remove(key)
        super(TreapHashSet, self).remove(key)

    def discard(self, key):
        if key in self.keys:
            self.remove(key)

    def __contains__(self, key):
        return key in self.keys

    def __repr__(self):
        return 'TreapHashSet({})'.format(list(self))


class TreapHashMap(TreapMultiSet):
    def __init__(self, data=None):
        if data:
            self.map = dict(data)
            super(TreapHashMap, self).__init__(self.map.keys())
        else:
            self.map = dict()

    def __setitem__(self, key, value):
        if key not in self.map:
            super(TreapHashMap, self).add(key)
        self.map[key] = value

    def __getitem__(self, key):
        return self.map[key]

    def add(self, key):
        raise TypeError("add on TreapHashMap")

    def get(self, key, default=None):
        return self.map.get(key, default=default)

    def remove(self, key):
        self.map.pop(key)
        super(TreapHashMap, self).remove(key)

    def discard(self, key):
        if key in self.map:
            self.remove(key)

    def __contains__(self, key):
        return key in self.map

    def __repr__(self):
        return 'TreapHashMap({})'.format(list(self))


left_child = [0]
right_child = [0]
treap_keys = [0]
treap_prior = [0.0]


def treap_builder(sorted_data):
    """Build a treap in O(n) time using sorted data"""

    def build(begin, end):
        if begin == end:
            return 0
        mid = (begin + end) // 2
        root = treap_create_node(sorted_data[mid])
        left_child[root] = build(begin, mid)
        right_child[root] = build(mid + 1, end)

        # sift down the priorities
        ind = root
        while True:
            lc = left_child[ind]
            rc = right_child[ind]

            if lc and treap_prior[lc] > treap_prior[ind]:
                if rc and treap_prior[rc] > treap_prior[rc]:
                    treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
                    ind = rc
                else:
                    treap_prior[ind], treap_prior[lc] = treap_prior[lc], treap_prior[ind]
                    ind = lc
            elif rc and treap_prior[rc] > treap_prior[ind]:
                treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
                ind = rc
            else:
                break
        return root

    return build(0, len(sorted_data))


def treap_create_node(key):
    treap_keys.append(key)
    treap_prior.append(random.random())
    left_child.append(0)
    right_child.append(0)
    return len(treap_keys) - 1


def treap_split(root, key):
    left_pos = right_pos = 0
    while root:
        if key < treap_keys[root]:
            left_child[right_pos] = right_pos = root
            root = left_child[root]
        else:
            right_child[left_pos] = left_pos = root
            root = right_child[root]
    left, right = right_child[0], left_child[0]
    right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
    return left, right


def treap_merge(left, right):
    where, pos = left_child, 0
    while left and right:
        if treap_prior[left] > treap_prior[right]:
            where[pos] = pos = left
            where = right_child
            left = right_child[left]
        else:
            where[pos] = pos = right
            where = left_child
            right = left_child[right]
    where[pos] = left or right
    node = left_child[0]
    left_child[0] = 0
    return node


def treap_insert(root, key):
    if not root:
        return treap_create_node(key)
    left, right = treap_split(root, key)
    return treap_merge(treap_merge(left, treap_create_node(key)), right)


def treap_insert_unique(root, key):
    if not root:
        return treap_create_node(key), False
    left, right = treap_split(root, key)
    if left and treap_keys[left] == key:
        return treap_merge(left, right), True
    return treap_merge(treap_merge(left, treap_create_node(key)), right), False


def treap_erase(root, key):
    if not root:
        raise KeyError(key)
    if treap_keys[root] == key:
        return treap_merge(left_child[root], right_child[root])
    node = root
    while root and treap_keys[root] != key:
        parent = root
        root = left_child[root] if key < treap_keys[root] else right_child[root]
    if not root:
        raise KeyError(key)
    if root == left_child[parent]:
        left_child[parent] = treap_merge(left_child[root], right_child[root])
    else:
        right_child[parent] = treap_merge(left_child[root], right_child[root])

    return node


def treap_ceiling(root, key):
    while root and treap_keys[root] < key:
        root = right_child[root]
    if not root:
        return 0
    min_node = root
    min_key = treap_keys[root]
    while root:
        if treap_keys[root] < key:
            root = right_child[root]
        else:
            if treap_keys[root] < min_key:
                min_key = treap_keys[root]
                min_node = root
            root = left_child[root]
    return min_node


def treap_higher(root, key):
    while root and treap_keys[root] <= key:
        root = right_child[root]
    if not root:
        return 0
    min_node = root
    min_key = treap_keys[root]
    while root:
        if treap_keys[root] <= key:
            root = right_child[root]
        else:
            if treap_keys[root] < min_key:
                min_key = treap_keys[root]
                min_node = root
            root = left_child[root]
    return min_node


def treap_floor(root, key):
    while root and treap_keys[root] > key:
        root = left_child[root]
    if not root:
        return 0
    max_node = root
    max_key = treap_keys[root]
    while root:
        if treap_keys[root] > key:
            root = left_child[root]
        else:
            if treap_keys[root] > max_key:
                max_key = treap_keys[root]
                max_node = root
            root = right_child[root]
    return max_node


def treap_lower(root, key):
    while root and treap_keys[root] >= key:
        root = left_child[root]
    if not root:
        return 0
    max_node = root
    max_key = treap_keys[root]
    while root:
        if treap_keys[root] >= key:
            root = left_child[root]
        else:
            if treap_keys[root] > max_key:
                max_key = treap_keys[root]
                max_node = root
            root = right_child[root]
    return max_node


def treap_min(root):
    if not root:
        raise ValueError('min on empty treap')
    while left_child[root]:
        root = left_child[root]
    return root


def treap_max(root):
    if not root:
        raise ValueError('max on empty treap')
    while right_child[root]:
        root = right_child[root]
    return root


def main():
    n = int(input())
    t = TreapMultiSet([int(x) for x in input().split()])
    A, B = [], []
    while len(t) > 2:
        a, b = t.min(), t.max()
        t.remove(a), t.remove(b)
        A.append(a), B.append(b)
        t.add(a - b)
    a, b = t.min(), t.max()
    print(b - a)
    print(a, b)
    for a, b in zip(A, B):
        print(a, b)


# region fastio

BUFSIZE = 8192


class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

    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("\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()


class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()


def print(*args, **kwargs):
    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()


sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    arr = list(map(int,input().split()))
    zero = 0
    pos = []
    neg = []
    for i in arr:
        if i > 0:
            pos.append(i)
        elif i < 0:
            neg.append(abs(i))
        else:
            zero += 1

    total = 0
    ans = []
    if pos and neg:
        total = sum(pos)+sum(neg)
        curr = -neg[0]
        for i in range(len(pos)-1):
            ans.append((curr,pos[i]))
            curr = curr-pos[i]

        ans.append((pos[-1],curr))         
        curr = pos[-1]-curr

        for i in range(1,len(neg)):
            ans.append((curr,-neg[i]))
            curr = curr+neg[i]
    else:
        arr.sort()
        if neg:
            arr.reverse()
        curr = arr[0]
        for i in range(n-2):
            ans.append((curr,arr[i]))
            curr = curr-arr[i]

        if pos:
            ans.append((arr[-1],curr))
            total = arr[-1]-curr
        else:
            ans.append((curr,arr[-1]))
            total = curr-arr[-1]

    print(total)
    for i in ans:
        print(i[0],i[1])
        


main()

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
#print(a)
s=[]
ans=[]
i=2
while i!=n:
    z=min(a)-max(a)
    s.append(min(a))
    s.append(max(a))
    ans.append(s)
    a.remove(min(a))
    a.remove(max(a))
    a.append(z)
    s=[]
    i+=1
#print(z)
#print(a)
print(max(a)-min(a))
s.append(max(a))
s.append(min(a))
ans.append(s)
i=0
#print(ans)
while i!=len(ans):
    print(ans[i][0],ans[i][1])
    i+=1

Submission status: Wrong Answer

Solution code:
from collections import deque

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

while len(q) > 2:
    max_tmp = q.pop()
    min_tmp = q.popleft()
    steps.append((min_tmp, max_tmp))
    min_tmp -= max_tmp
    q.appendleft(min_tmp)

max_tmp = q.pop()
min_tmp = q.popleft()
steps.append((max_tmp, min_tmp))
m = max_tmp - min_tmp
print(m)
for x, y in steps:
    print('{} {}'.format(x, y))

Submission status: Wrong Answer

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


def answer(A, ans):
    ans.append([A[0], A[1]])
    A[0] = A[0]-A[1]
    del A[1]
    return A, ans

A = sorted(A)

while True:
    if len(A) == 2:
        M = A[1]-A[0]
        ans.append([A[1], A[0]])
        break
    A, ans = answer(A, ans)

print(M)
for d in ans:
    print(d[0], d[1])

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [0]*N
A = list(map(int, input().split()))
ans = int(0)
x = int(0)
y = int(0)

As = sorted(A)

for i in range(N):
    ans += As[i]

ans -=As[0]*2
print(ans)

x = As[0]
for i in range(N-2):
    y = As[i+1]
    print(x,y)
    x = x - y

y = x
x = As[N-1]
print(x,y)

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
A = LIST()

flag_plus = False
flag_minus = False
plus_list = []
minus_list = []
zero_list = []
for i in A:
	if i < 0:
		flag_minus = True
		minus_list.append(i)
	elif i > 0:
		flag_plus = True
		plus_list.append(i)
	else:
		zero_list.append(0)

# print(plus_list)
# print(minus_list)
if flag_plus and flag_minus:  # 正も負もある
	print(sum([abs(x) for x in A]))
	tmp1 = minus_list.pop(0)
	tmp2 = plus_list.pop(0)
	if plus_list:
		print(tmp1, plus_list[0])
		tmp1 = tmp1 - plus_list[0]  # tmp1 はマイナスの集約
		for i in range(1, len(plus_list)):  # マイナスにひく
			print(tmp1, plus_list[i])
			tmp1 = tmp1 - plus_list[i]

	if minus_list:
		print(tmp2, minus_list[0])
		tmp2 = tmp2 - minus_list[0]  # tmp2は プラスの集約
		for i in range(1, len(minus_list)):
			print(tmp2, minus_list[i])
			tmp2 = tmp2 - minus_list[i]
	for i in range(len(zero_list)):
		print(tmp2, 0)
	print(tmp2, tmp1)


elif flag_plus and (not flag_minus):  # 正のみ
	A_min = min(A)
	print(sum(A)-2*A_min)
	print(A_min, A[0])
	tmp = A_min - A[0]
	for i in range(1, N-1):
		if i != N-2:
			print(tmp, A[i])
			tmp = tmp - A[i]
		else:
			print(A[i], tmp)
elif (not flag_plus) and flag_minus:  # 負のみ
	A_max = max(A)
	print(sum([abs(x) for x in A])+2*A_max)
	A.remove(A_max)
	print(A_max, A[0])
	tmp = A_max - A[0]
	for i in range(1, N-1):
		print(tmp, A[i])
		tmp = tmp-A[i]
else:  # 正も負もなし(全部0)
	print(0)
	for i in range(N-1):
		print(0, 0)

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    A = sorted(list(map(int, input().split())))
    cnt0 = 0
    cnt1 = 0
    cnt2 = 0
    for i in range(N):
        if A[i]<0:
            cnt1+=1
        elif A[i]>0:
            cnt2+=1
        else:
            cnt0+=1
    if 0<cnt2+cnt0<N:
        M = sum(list(map(abs, A)))
        print(M)
        hu = A[0]
        sei = A[cnt1]
        tmp1 = sei
        for i in range(1, cnt1):
            print(tmp1, A[i])
            tmp1-=A[i]
        tmp2 = hu
        for i in range(cnt1+1, N):
            print(tmp2, A[i])
            tmp2-=A[i]
        print(tmp1, tmp2)
    elif cnt2==0:
        if cnt0 >0:
            M = sum(list(map(abs, A)))
            print(M)
            hu = A[0]
            sei = A[cnt1]
            tmp1 = sei
            for i in range(1, cnt1):
                print(tmp1, A[i])
                tmp1-=A[i]
            tmp2 = hu
            for i in range(cnt1+1, N):
                print(tmp2, A[i])
                tmp2-=A[i]
            print(tmp1, tmp2)
        else:
            M = -sum(A)+A[-1]*2
            print(M)
            tmp = A[-1]
            for i in range(N-1):
                print(tmp, A[i])
                tmp = tmp-A[i]
    else:
        M = sum(A)-A[0]*2
        print(M)
        tmp = A[0]
        for i in range(1, N-1):
            print(tmp, A[i])
            tmp = tmp-A[i]
        print(A[N-1], tmp)
solve()

Submission status: Wrong Answer

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

li.sort()
result=[]
for i in range(len(li)-1):
  result.append([li.pop(0),li.pop(len(li)-2)])
  a=result[i][0]-result[i][1]
  li.insert(0,a)
  
print(-li[0])
a=result[len(result)-1][1]
result[len(result)-1][1]=result[len(result)-1][0]
result[len(result)-1][0]=a
for i in range(len(result)):
  print(result[i][0],result[i][1])

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
b=[]
if n%2==0:
    for k in range(n//2):
        b.append(a[n//2+k])
        b.append(a[n//2-k-1])
    print(sum(a[n//2:])-sum(a[:n//2]))
    for i in range(n-1):
        print(str(b[-2])+" "+str(b[-1]))
        tmp=b[-1]
        b.pop(-1)
        b[-1]=b[-1]-tmp

else:
    for k in range(n//2):
        b.append(a[n//2+k])
        b.append(a[n//2-k-1])
    b.append(a[-1])
    print(sum(a[n//2:])-sum(a[:n//2]))
    for i in range(n-1):
        print(str(b[-2])+" "+str(b[-1]))
        tmp=b[-1]
        b.pop(-1)
        b[-1]=b[-1]-tmp

Submission status: Wrong Answer

Solution code:
N = int(input())

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

maximum = max(A_list)
A_list.pop(A_list.index(max(A_list)))

max_list = [0] * (N - 1)
min_list = [0] * (N - 1)

for i in range(N - 2):
    max_list[i] = max(A_list)
    A_list.pop(A_list.index(max_list[i]))
    min_list[i] = min(A_list)
    A_list.pop(A_list.index(min_list[i]))
    tmp = min_list[i] - max_list[i]
    A_list.append(tmp)
answer = maximum - sum(A_list)

print(answer)
for i in range(N - 2):
    print(max_list[i], min_list[i])
print(maximum, A_list[0])

Submission status: Wrong Answer

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

suma = 0 
for item in a:
    suma += abs(item)

min_id = -1; min_val = 10**5
max_id = -1; max_val = -10**5
plus_id = -1
minus_id = -1
zero_id = -1

for i, item in enumerate(a):
    if min_val > item:
        min_val = item
        min_id = i
    if max_val < item:
        max_val = item
        max_id = i
    if item == 0:
        zero_id = i
    elif item > 0:
        plus_id = i
    elif item < 0:
        minus_id = i
# All plus
if minus_id == -1:
    print(suma - 2 * min_val)
    val = min_val
    not_initialized = True
    for i, item in enumerate(a):
        if item == min_val and not_initialized:
            not_initialized = False
            continue
        if i == len(a) - 1 - not_initialized:
            print(item, val)
            continue
        print(val, item)
        val -= item
# All minus
if plus_id == -1:
    print(suma - 2 * abs(max_val))
    val = max_val
    not_initialized = True
    for i, item in enumerate(a):
        if item == max_val and not_initialized:
            initialized = False
            continue
        print(val, item)
        val -= item
# both of tem
if plus_id != -1 and minus_id != -1:
    print(suma)
    not_initialized_min = True
    not_initialized_max = True
    minv = min_val
    maxv = max_val
    for i, item in enumerate(a):
        if item == min_val and not_initialized_min:
            not_initialized_min = False
            continue
        if item == max_val and not_initialized_max:
            not_initialized_max = False
            continue
        if item <= 0:
            print(maxv, item)
            maxv -= item
        elif item > 0:
            print(minv, item)
            minv -= item
    print(maxv, minv)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 20:54:34 2019

@author: Yamazaki Kenichi
"""

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

A.sort()

tmp = A[0]
T = []
for i in range(1,N):
    T.append([tmp,A[i]])
    tmp = tmp - A[i]
print(-tmp)
T[-1][0], T[-1][1] = T[-1][1], T[-1][0]
for t in T:
    print(' '.join(map(str,t)))

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    A = sorted(list(map(int, input().split())))
    cnt0 = 0
    cnt1 = 0
    cnt2 = 0
    for i in range(N):
        if A[i]<0:
            cnt1+=1
        elif A[i]>0:
            cnt2+=1
        else:
            cnt0+=1
    if 0<cnt2+cnt0<N:
        M = sum(list(map(abs, A)))
        print(M)
        hu = A[0]
        sei = A[cnt1]
        tmp1 = sei
        for i in range(1, cnt1):
            print(tmp1, A[i])
            tmp1-=A[i]
        tmp2 = hu
        for i in range(cnt1+1, N):
            print(tmp2, A[i])
            tmp2-=A[i]
        print(tmp1, tmp2)
    elif cnt2==0:
        if cnt0 >0:
            M = sum(list(map(abs, A)))
            print(M)
            hu = A[0]
            sei = A[cnt1]
            tmp1 = sei
            for i in range(1, cnt1):
                print(tmp1, A[i])
                tmp1-=A[i]
            tmp2 = hu
            for i in range(cnt1+1, N):
                print(tmp2, A[i])
                tmp2-=A[i]
            print(tmp1, tmp2)
        else:
            M = -sum(A)+A[-1]*2
            print(M)
            tmp = A[-1]
            for i in range(N-1):
                print(tmp, A[i])
                tmp = tmp-A[i]
    else:
        M = sum(A)-A[0]*2
        print(M)
        tmp = A[0]
        for i in range(1, N-1):
            print(tmp, A[i])
            tmp = tmp-A[i]
        print(A[N-1], tmp)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(map(int, input().strip().split(' ')))
 
count = 0
 
for i in range(n):
    minj = i
    for j in range(i + 1, n):
        if s[j] < s[minj]:
            minj = j
     
    s[i], s[minj] = s[minj], s[i]

for i in range(n - 1):
    if (i != n -2):
        s[i + 1] = s[i] - s[i + 1]
    else:
        ans = s[i + 1] - s[i]

print(s[n -1], end =' ')
print(s[n - 2])

Submission status: Wrong Answer

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

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

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

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

Submission status: Wrong Answer

Solution code:
from collections import deque

N = int(input())
A = list(map(int, input().split()))
A = sorted(A)
q = deque(A)
max_tmp = q.pop()
min_tmp = q.popleft()
steps = list()

while len(q) > 1:
    max_tmp2 = q.pop()
    min_tmp2 = q.popleft()
    steps.append((min_tmp2, max_tmp2))
    min_tmp2 -= max_tmp2
    q.appendleft(min_tmp2)

if q:
    max_tmp2 = q.pop()
    steps.append((min_tmp, max_tmp2))
    min_tmp -= max_tmp2

steps.append((max_tmp, min_tmp))
m = max_tmp - min_tmp
print(m)
for x, y in steps:
    print('{} {}'.format(x, y))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
#print(a)
s=[]
ans=[]
i=2
while i!=n:
    z=min(a)-max(a)
    s.append(min(a))
    s.append(max(a))
    ans.append(s)
    a.remove(min(a))
    a.remove(max(a))
    a.append(z)
    s=[]
    i+=1
#print(z)
#print(a)
print(max(a)-min(a))
s.append(max(a))
s.append(min(a))
ans.append(s)
i=0
while i!=len(ans):
    print(ans[i][0],ans[i][0])
    i+=1

Submission status: Wrong Answer

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

a_max = a.pop(a.index(max(a)))
a_min = a.pop(a.index(min(a)))
s = a_min
if n == 2:
    print(a_max - a_min)
    print(a_max, a_min)
    
else:
    t = [a_min]
    
    for v in a:
        s -= v
        t.append(s)
    t.append(a_max)
    ans = a_max - s
    print(ans)
    for i in range(0, n-2):
        print(t[i], a[i])
    print(a_max, s)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

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


pmin = 10**9
pind = -1
qmax =  -10**9
qind = -1

for j,i in enumerate(a):
    if 0 <= i < pmin:
        pmin = i
        pind = j
    if qmax < i < 0:
        qmax = i 
        qind = j

#print(a)
#print(pmin,qmax, "pmin", "pmax")

pmax = pmin

if pind == -1: # 非負が0個
    ans = -sum(a) + 2*a[qind]
    print(ans)
    for i, ai in enumerate(a):
        if i != qind:
            print(qmax,ai)
            qmax -= ai
#            print(qind, i)
    exit()
    
elif qind == -1: # 負が0個
    ans = sum(a) - 2*a[pind]
    print(ans)
    if pind == 0:
        for i in range(2,n):
            print(pmax, a[i])
            pmax -= a[i]
        print(a[1], pmax)
    else:
        for i in range(1,n):
            if i==pind: continue
            print(pmax, a[i])
            pmax -= a[i]
        print(a[0], pmax)
    exit()

else:
#    print("pq")
    ans = 0
    for ai in a:
        ans += abs(ai)
    print(ans)
    for i, ai in enumerate(a):
        if i == pind or i == qind: continue
        if ai < 0:
            print(pmax, ai)
            pmax -= ai
        if ai > 0:
            print(qmax,ai)
            qmax -= ai
    print(pmax,qmax)

Submission status: Wrong Answer

Solution code:
import bisect 

n=int(input())
l=list(map(int,input().split()))
l.sort()
#dq=deque(l)
if l[0]>=0:
    #print('hello')
    a=l[0]
    ans=0
    for i in range(n):
        ans+=l[i]
    print(ans-2*l[0])
    for i in range(1,n-1):
        print(a,l[i])
        a-=l[i]
    print(l[-1],a)
elif l[-1]<=0:
    #print('hello')
    a=l[-1]
    ans=l[-1]
    for i in range(n-1):
        ans-=l[i]
    print(ans)
    for i in range(n-1):
        print(a,l[i])
        a-=l[i]
else:
    #print('hello')
    idx=bisect.bisect(l,0)
    ans=0
    for i in range(n):
        if l[i]>=0:
            ans+=l[i]
        else:
            ans-=l[i]
    print(ans)
    a=l[0]
    for i in range(idx,n-1):
        print(a,l[i])
        a-=l[i]
    for i in range(1,a):
        print(l[-1],l[i])
    print(l[-1],a)

Submission status: Wrong Answer

Solution code:
import heapq

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

max_heap = []
min_heap = []
ope = []

for i in range(N):
    heapq.heappush(max_heap,(-A[i], A[i]))
    heapq.heappush(min_heap,(A[i], A[i]))

M = 0
for i in range(N-1):
    if i==N-2:
        x, y = heapq.heappop(max_heap)[1], heapq.heappop(min_heap)[1]
        M = x - y
        ope.append("" + str(x) + " " + str(y))
    else:
        x, y = heapq.heappop(min_heap)[1], heapq.heappop(max_heap)[1]
        m = x - y
        ope.append("" + str(x) + " " + str(y))
        heapq.heappush(max_heap,(-m, m))
        heapq.heappush(min_heap,(m, m))

print(M)
print("\n".join(ope))