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)
    A.append(a), B.append(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 gcd_core(a, b):
    if b == 0:
        return a
    else:
        return gcd_core(b, a % b)


def gcd(arr):
    g = gcd_core(arr[0], arr[1])
    for i in range(2, len(arr)):
        g = gcd_core(g, arr[i])
    return g


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

# print(arr)

step = n-1

out = []

if step%2 ==0:
    A = arr[-1]
    dist = 0
    # print(A)
    for i in range(step):
        if i%2==0:
            out.append([arr[0+dist],A])
            A = arr[0+dist]-A
            dist+=1

        else:
            out.append([arr[-1-dist],A])
            A = arr[-1-dist]-A

else:
    A = arr[-1]
    dist = 0
    for i in range(step):
        if i%2==0:
            out.append([A,arr[0+dist]])
            A = A-arr[0+dist]
            dist+=1

        else:
            out.append([A,arr[-1-dist]])
            A = A-arr[-1-dist]

print(A)
for i in range(step):
    print(out[i][0]," ",out[i][1])

Submission status: Wrong Answer

Solution code:
import numpy as np
N = int(input())
A = sorted(list(map(int, input().split())))
B = np.array(A)
tmp = set(B)

if len(tmp) > 1:
    print(sum(np.abs(B)))
else:
    print((N - 2) * abs(A[0]))

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

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
elif 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
elif 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)
else:
    print(0)
    for i in range(n-1):
        print(0, 0)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = list(map(int,input().split()))
a = sorted(a)
#print(a)
if a[0] < 0:
    ans = 0
    negn = 0
    for i in range(n):
        ans += abs(a[i])
        if a[i]<0:
            negn += 1
    print(ans)
    s = a[0]
    for i in range(negn , n-1):
        print(s,a[i])
        s = s-a[i]
    k = a[-1]
    for i in range(1,negn):
        print(k,a[i])
        k = k-a[i]
    print(k,s)

else:
    ans = 0
    for i in range(n):
        ans += abs(a[i])
    print(ans-2*a[0])
    m = a[0]
    for i in range(1,n-1):
        print(m,a[i])
        m = m-a[i]
    print(a[-1],m)

Submission status: Wrong Answer

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

aLength=len(listA)
bigL = listA[aLength//2:]
smallL = listA[:aLength//2]
current = 0
index = 0
smallI = 0
bigI = 0
answerL = []
if aLength%2== 0:
    while index < aLength:
        if index%2==0:
            if smallL[smallI]-current < current-smallL[smallI]:
                answerL.append(str(smallL[smallI])+" "+str(current))
                current=smallL[smallI]-current
            else:
                answerL.append(str(current)+" "+str(smallL[smallI]))
                current-=smallL[smallI]
            smallI+=1
        else:
            if bigL[bigI]-current > current-bigL[bigI]:
                answerL.append(str(bigL[bigI])+" "+str(current))
                current=bigL[bigI]-current
            else:
                answerL.append(str(current)+" "+str(bigL[bigI]))
                current-=bigL[bigI]
            bigI+=1
        index+=1
else:
    while index < aLength:
        if index % 2 == 1:
            if smallL[smallI]-current < current-smallL[smallI]:
                answerL.append(str(smallL[smallI])+" "+str(current))
                current=smallL[smallI]-current
            else:
                answerL.append(str(current)+" "+str(smallL[smallI]))
                current-=smallL[smallI]
            smallI+=1
        else:
            if bigL[bigI]-current > current-bigL[bigI]:
                answerL.append(str(bigL[bigI])+" "+str(current))
                current = bigL[bigI]-current
            else:
                answerL.append(str(current)+" "+str(bigL[bigI]))
                current -= bigL[bigI]
            bigI += 1
        index += 1

print(current)
del answerL[0]
for ans in answerL:
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque  # 双方向キュー
from collections import defaultdict  # 初期化済み辞書
from heapq import heapify, heappush, heappop, heappushpop  # プライオリティキュー
from bisect import bisect_left, bisect_right  # 二分探索
#import numpy as np  # 1.8.2
#import scipy  # 0.13.3

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N = i2n()
    A = i2nn()
    A.sort()
    b = N % 2
    log = []
    if b == 0:
        x = 0
        y = A[0]
        for i in range(1, N):
            i2 = int(i / 2)
            if i % 2 == 0:
                x = A[i2]
            else:
                x = A[N-1-i2]
            log.append('%d %d' % (x, y))
            y = x - y
    else:
        x = 0
        y = A[N-1]
        for i in range(1, N):
            i2 = int(i / 2)
            if i % 2 == 0:
                x = A[N-1-i2]
            else:
                x = A[i2]
            log.append('%d %d' % (x, y))
            y = x - y
    print(y)
    for s in log:
        print(s)

main()

Submission status: Wrong Answer

Solution code:
import numpy as np

m = int(input())
a = np.array([int(i) for i in input().split()])
a = -np.sort(-a)
b = np.array_split(a,2)

print(np.sum(b[0]) - np.sum(b[1]))
i = np.array(range(len(b[0])))
b = np.insert(b[1], i, b[0][i])

y = b[-1]
for i in range(len(b)-2, -1, -1):
    x = b[i]
    print("{} {}".format(x, y))
    y = x - y

Submission status: Wrong Answer

Solution code:
N = int(input())

H = list(map(int, input().split()))
H.sort()

# answer
ans = ""
sum_ans = 0
for i in range(N - 1, 0, -1):
    if i == N - 1:
        if i % 2:
            ans += "{0} {1}\n".format(H[-1], H[0])
            sum_ans = H[-1] - H[0]
        else:
            ans += "{0} {1}\n".format(H[0], H[-1])
            sum_ans = - H[-1] + H[0]
    else:
        v = H[N - 1 - i]
        is_right = (v >= 0) ^ (i % 2)
        if is_right:
            ans += "{0} {1}\n".format(sum_ans, v)
            sum_ans = sum_ans - v
        else:
            ans += "{0} {1}\n".format(v, sum_ans)
            sum_ans = v - sum_ans

ans = "{}\n".format(sum_ans) + ans

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = list(map(int, input().split()))
A.sort()
q = deque(A)
ansq = deque()
i = 0
while i != N - 2:
    """if i % 2 == 0:
        l, r = q.popleft(), q.pop()
        q.appendleft(l - r)
        ansq.append((l,  r))
    else:
        l, r = q.popleft(), q.pop()
        q.append(r - l)
        ansq.append((r,  l))"""
    l, r = q.popleft(), q.pop()
    if l < 0 and r < 0: # どちらもマイナス
        if l < r:
            q.append(r - l)
            ansq.append((r, l))
        else:
            q.append(l - r)
            ansq.append((l, r))
    elif l >= 0 and r >= 0: # どちらもプラス
        if l < r:
            q.appendleft(l - r)
            ansq.append((l, r))
        else:
            q.appendleft(r - l)
            ansq.append((r, l))
    else: # 異符号
        if l < r:
            q.appendleft(l - r)
            ansq.append((l, r))
        else:
            q.append(r - l)
            ansq.append((r, l))
    i += 1
print(q[1] - q[0])
for ans in ansq:
    print("{} {}".format(ans[0], ans[1]))
print(q[1], q[0])

Submission status: Wrong Answer

Solution code:
import sys
# input = sys.stdin.readline
inf = 10 ** 18

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

from collections import deque

A = deque(sorted(A))

pm = N % 2
ans = []
for i in range(N - 1):
    # print("#", list(A))
    A_min = A.popleft()
    A_min2 = A.popleft()
    if i == N - 2:
        ans.append((A_min2, A_min))
        A.append(A_min2 - A_min)
    else:
        ans.append((A_min, A_min2))
        A.appendleft(A_min - A_min2)

print(A[0])
for x, y in ans: print(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[1] = A[0]-A[1]
    return A[1:], 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)
    A = sorted(A)

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

Submission status: Wrong Answer

Solution code:
from heapq import heapify, heappush, heappop
def solve():
    n = int(input())
    A = list(map(int, input().split()))
    heapify(A)
    ans = []
    for i in range(n - 2):
        a = heappop(A)
        b = heappop(A)
        ans.append(str(a) + " " + str(b))
        heappush(A, a - b)
    a = heappop(A)
    b = heappop(A)
    ans.append(str(b) + " " + str(a))
    heappush(A, b - a)
    print(heappop(A))
    print(*ans, sep="\n")
solve()

Submission status: Wrong Answer

Solution code:
n = int(input())

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

nums.sort()

print(nums)
if nums[0] >= 0:
	# all 0以上
	print(sum(list(map(abs, nums))) - 2 * nums[0])

	hikareru = nums[0]
	for idx in range(2,n):
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]

	print("{} {}".format(nums[1], hikareru) )

elif nums[-1] <= 0:
	# all 0以下
	print(sum(list(map(abs, nums))) - 2 * (-1)*nums[-1] )

	hikareru = nums[-1]
	for idx in range(n-1):
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]

else:
	print(sum(list(map(abs, nums))) )

	hikareru = nums[0]
	idx = n-2
	while True:
		if nums[idx] < 0:
			break
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]
		idx -= 1

	hiku = hikareru
	print("{} {}".format(nums[n-1], hiku) )
	hikareru = nums[n-1] -  hiku

	idx = 1
	while True:
		if nums[idx] >= 0:
			break
		print("{} {}".format(hikareru, nums[idx]) )
		hikareru -= nums[idx]
		idx += 1

Submission status: Wrong Answer

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

from collections import defaultdict

N = int(input())
X = list(map(int, input().rstrip().split(' ')))
X = sorted(X)

count_minus = sum([1 if x < 0 else 0 for x in X])

if N == 2:
    print(X[1] - X[0])
    print(X[1], X[0])
else:
    ope = []
    if count_minus == N:
        max_value = X[-1] - X[0]
        min_value = X[2]
        ope.append([X[-1], X[0]])
        start = 1
        end = N - 2
    elif count_minus == 0:
        min_value = X[0] - X[-1]
        max_value = X[-2]
        ope.append([X[0], X[-1]])
        start = 1
        end = N - 2
    else:
        min_value = X[0]
        max_value = X[-1]
        start = 1
        end = N-1

    for i in range(start, end):
        if X[i] < 0:
            ope.append([max_value, X[i]])
            max_value -= X[i]
        else:
            ope.append([min_value, X[i]])
            min_value -= X[i]
    ope.append([max_value, min_value])
    
    print(max_value - min_value)
    for i in range(len(ope)):
        a, b = ope[i]
        print(a, b)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n = int(input()) 
a = [int(i) for i in input().split()]
#print(n,a)

from collections import deque
#n=3
#a=[1, 1, 1]
a.sort()
a=deque(a)
ans=deque() 

while len(a)>1:
    if len(a)%2==1:
        mina=a.popleft()
        maxa=a.pop()
#        print(mina,maxa)
        ans.append((mina,maxa))
        val=mina-maxa
        a.appendleft(val)
#        print(a)
    else:
        mina=a.popleft()
        maxa=a.pop()
#        print(maxa,mina)
        ans.append((maxa,mina))
        val=maxa-mina
        a.appendleft(val)
#        print(a)        

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

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [int(s) for s in input().split(' ')]
A.sort()
print(sum(A[1:]) - A[0])
while(len(A) > 2):
    print("{} {}".format(A[0], A[1]))
    A = [A[0] - A[1]] + A[2:]
print(A[1], A[0])

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = list(map(int, input().split()))
bb = deque()
x = [0]*(N-1)
y = [0]*(N-1)
for i in range(N):
    if A[i] < 0:
        bb.appendleft(A[i])
    else:
        bb.append(A[i])
start_bool = 1 if N % 2 == 0 else -1
for i in range(N-1):
    l = bb.popleft()
    r = bb.pop()
    if start_bool < 0:
        if l > r:
            ret = r - l
            x[i] = r
            y[i] = l
        else:
            ret = l - r
            x[i] = l
            y[i] = r
    else:
        if l > r:
            ret = l - r
            x[i] = l
            y[i] = r
        else:
            ret = r - l
            x[i] = r
            y[i] = l
    if ret > 0:
        bb.append(ret)
    else:
        bb.appendleft(ret)
    start_bool *= -1
print(bb.pop())
for i in range(N-1):
    print(x[i], y[i])

Submission status: Wrong Answer

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort()
s = [0 for i in range(n)]
ans = -1e9
pos = 0
flag = True
s[0] = a[0]
for i in range(n):
  s[i] = s[i-1]+a[i]
for i in range(n):
  if i==0:
    if ans < s[n-1]-s[i]-a[i]:
      pos = i
      flag = False
      ans = s[n-1]-s[i]-a[i]
    if ans < -(s[n-1]-s[i])+a[i]:
      pos = i
      flag = True
      ans = -(s[n-1]-s[i])+a[i]
  else:
    if ans < s[i-1]+s[n-1]-s[i]-a[i]:
      pos = i
      flag = False
      ans = s[i-1]+s[n-1]-s[i]-a[i]
    if ans < -s[i-1]-(s[n-1]-s[i])+a[i]:
      pos = i
      flag = True
      ans = -s[i-1]-(s[n-1]-s[i])+a[i]
print(ans)
cur = a[pos]
a.remove(cur)
if flag:
  for i in range(n-1):
    print(cur, a[i])
    cur = cur-a[i]
else:
  for i in range(n-2):
    print(cur, a[i])
    cur = cur-a[i]
  print(a[n-2], cur)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = sorted(map(int,input().split()))[::-1]
B = A[:(N+1)//2]
i = (N+1)//2
if B[-1]<0:
    for i in range(1,N+1//2):
        if B[i]<0:
            B = B[:i]
            break
C = A[i:2*i][::-1]
D = A[2*i:]
ans = []
if (len(B)+len(C))%2:
    M = B.pop()
else:
    M = C.pop()
while B:
    if len(B)>len(C):
        p = B.pop()
    else:
        p = C.pop()
    ans.append((p,M))
    M = p - M
for d in D:
    ans.append((M,d))
    M = M - d
print(M)
for o in ans:
    print(*o)

Submission status: Wrong Answer

Solution code:
import numpy as np
N = int(input())
A = sorted(list(map(int, input().split())))
B = np.array(A)
tmp = set(B)

if len(tmp) > 1:
    print(sum(np.abs(B)))
else:
    print((N - 2) * A[0])

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

Submission status: Wrong Answer

Solution code:


def gcd_core(a, b):
    if b == 0:
        return a
    else:
        return gcd_core(b, a % b)


def gcd(arr):
    g = gcd_core(arr[0], arr[1])
    for i in range(2, len(arr)):
        g = gcd_core(g, arr[i])
    return g


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

# print(arr)

step = n-1

if step%2 ==0:
    A = arr[-1]
    dist = 0
    # print(A)
    for i in range(step):
        if i%2==0:
            print(arr[0+dist]," ",A)
            A = arr[0+dist]-A
            dist+=1

        else:
            print(arr[-1-dist]," ",A)
            A = arr[-1-dist]-A

else:
    A = arr[-1]
    dist = 0
    for i in range(step):
        if i%2==0:
            print(A," ",arr[0+dist])
            A = A-arr[0+dist]
            dist+=1

        else:
            print(A," ",arr[-1-dist])
            A = A-arr[-1-dist]

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort()
if A[1] >= 0:
	print(sum(A) - 2 * A[0])
	y = A[0]
	for i in range(N - 2):
		print(y, A[i + 1])
		y -= A[i + 1]
	print(A[-1], y)
elif A[-1] < 0:
	print(-sum(A) + 2 * A[-1])
	y = A[-1]
	for i in range(N - 1):
		print(y, A[i])
		y -= A[i]
else:
	n = len([i for i in A if i < 0])
	print(-sum(A[:n]) + sum(A[n:]))
	y = A[0]
	for i in range(N - n - 1):
		print(y, A[-i - 2])
		y -= A[-i - 2]
	print(A[-1], y)
	y = A[-1] - y
	for i in range(n - 1):
		print(y, A[i + 1])

Submission status: Wrong Answer

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

for i in range(N - 1):
    if i != N - 1:
        A.sort()
        min = A[0]
        max = A[-1]
        kara.append([min, max])
        sa = min - max
        A = A[1:-1]
        A.append(sa)

abs(A[0])
for i in range(N-1):
    print(kara[i][0], kara[i][1])