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: Runtime Error

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    A = sorted(A)
    A_M = sorted(A)
    A_M[0] *= -1
    start = 0
    if N == 2:
        print(max(A) - min(A))
        print('{} {}'.format(max(A), min(A)))
        return
    for i in range(1, N-1):
        if A_M[i] < 0:
            A_M[i] *= -1
            start = i
    M = sum(A_M)
    print(M)
    if start == 0:
        for i in range(1, N):
            if i < N-1:
                if i == 1:
                    x = A[0]
                    y = A[1]
                else:
                    x = tmp
                    y = A[i]
            else:
                x = A[-1]
                y = tmp
            tmp = x - y
            print('{} {}'.format(x, y))
    elif start == N - 2:
        for i in range(1, N):
            if i == 1:
                x = A[-1]
                y = A[start]
            else:
                x = tmp
                y = A[start-i+1]
            tmp = x - y
            print('{} {}'.format(x, y))
    else:
        for i in range(1, N):
            if i == 1:
                x = A[start]
                y = A[start+1]
            elif 1 < i < N - 1 - start:
                x = tmp
                y = A[start+i]
            elif i == N - 1 - start:
                x = A[-1]
                y = tmp
            else:
                x = tmp
                y = A[start-(i-N-1-start)]
            tmp = x - y
            print('{} {}'.format(x, y))
    return


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
	n = int(input())
	a = list(map(int,input().split()))
	a.sort()
	if a[0] >= 0:
		plst = a
		nlst = []
		lnp = n
	elif a[-1] < 0:
		plst = []
		nlst = a
		lnp = 0
	else:
		temp = 0
		for i in range(1,n):
			if (a[i-1] <0) and (a[i] > 0):
				temp = i
				break
		plst = a[i:]
		nlst = a[:i]
		lnp = n-i
	anslst = []
	if n == 2:
		print(max(a)-min(a))
		print(max(a),min(a))
		return
	while lnp > 1:
		if lnp == n:
			if n == 2:
				anslst += [[plst[1],plst[0]]]
				print(plst[1]-plst[0])
				for i in anslst:
					print("{} {}".format(i[0],i[1]))
				return
			temp = plst[1]-plst[0]
			anslst +=[[plst[1],plst[0]]]
			if temp == 0:
				plst = [0]+plst[2:]
				n-=1
				lnp -= 1
			else:
				nlst += [temp]
				n-= 1
				plst = plst[2:]
				lnp -= 2
		else:
			anslst += [[nlst[-1],plst[0]]]
			nlst = nlst[:-1] + [nlst[-1]-plst[0]]
			plst = plst[1:]
			n-=1
			lnp -=1
	ans = plst[0]
	for i in nlst:
		anslst += [[ans,i]]
		ans -= i
	print(ans)
	for l in anslst:
		print("{} {}".format(l[0],l[1]))
	return

main()

Submission status: Runtime Error

Solution code:
from collections import deque

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

operation = []
for i in range(N-1):
    if i%2==0: # Negative
        x = A.pop()
        y = A.popleft()
        operation.append(f'{x} {y}')
        A.appendleft(y + x * -1)
    else: # Positive
        x = A.popleft()
        y = A.pop() 
        operation.append(f'{x} {y}')
        A.append(y + x * -1)

print(sum(list(A)))
for o in operation:
    print(o)

Submission status: Runtime Error

Solution code:
N = int(input())
List = list(map(int,input().split()))
List = sorted(List)
found = False
i = N//2 
while found == False and i < N:
    if List[i]>=0:
        found = True
    else:
        i = i+1

A = List[:i]
B = List[i:]
a = 0
y = 0
print(sum(B)-sum(A))
for k in range(N - i-1):
    x = B[k]
    if a != 0:
        print(x,y)
    y = x-y
    a += 1
    x = A[k]
    print(x,y)
    y = x-y
x = B[N-i-1]    
print(x,y)
x = x-y
for k in range(N-i-1,i):
    y = A[k]
    print(x,y)
    x = x - y

Submission status: Runtime Error

Solution code:
import bisect
from operator import itemgetter
import math
import collections
import functools
import itertools
import numpy as np
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N = I()
A = IL()
A.sort()

l,h = 0,0
if A[0] < 0:
  l = 1
if A[-1] >= 0:
  h = 1

f = 0
if l == 1 and h == 1:
  ans = 0
  for i in range(N):
    if A[i] < 0:
      ans -= A[i]
    else:
      ans += A[i]
  print(ans)

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

elif l == 0 and h == 1:
  print(sum(A[2:])-(A[0]-A[1]))
  tmp = A[0]
  for i in range(1,N-1):
    print(tmp,A[i])
    tmp -= A[i]
  else:
    print(A[i],tmp)
    
elif l == 1 and h == 0:
  print(abs(sum(A[2:]))+(A[0]-A[1]))
  tmp = A[0]
  for i in range(1,N):
    print(tmp,A[i])
    tmp -= A[i]

Submission status: Runtime Error

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__


def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    a.sort()

    if a[-1] <= 0:
        s = max(a)
        a.remove(s)

        X, Y = [], []
        for _ in range(n - 2):
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        ai = a.pop()
        X.append(s), Y.append(ai)

        print(s - ai)
        for x, y in zip(X, Y):
            print(x, y)
    elif a[0] >= 0:
        s = min(a)
        a.remove(s)

        X, Y = [], []
        for _ in range(n - 2):
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        ai = a.pop()
        X.append(ai), Y.append(s)

        print(ai - s)
        for x, y in zip(X, Y):
            print(x, y)
    else:
        s = min(a)
        a.remove(s)

        X, Y = [], []
        while a[-1] >= 0 and len(a) > 1:
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        a = [s] + a
        s = max(a)
        a.remove(s)

        while len(a) > 1:
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        ai = a.pop()
        X.append(s), Y.append(ai)

        print(s - ai)
        for x, y in zip(X, Y):
            print(x, y)

        ai = a.pop()
        X.append(ai), Y.append(s)

        print(ai - s)
        for x, y in zip(X, Y):
            print(x, y)

# 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: Runtime Error

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

Submission status: Runtime Error

Solution code:
n=int(input())
a=[int(i) for i in input().split()]
ans=0
a.sort()
a.reverse()
if n%2==0:
    p=n//2
else:
    p=n//2+1
c=1
lp=[]
lm=[]
for i in a:
    if i>0 and c<=p:
        ans+=i
        lp.append(i)
    else:
        ans-=i
        lm.append(i)
    c+=1
print(ans)
llp=len(lp)
llm=len(lm)
q=[]
i=0
j=0
k=0
o=0
while o==0:
    if llp>llm:
        if lp!=[] and lm!=[]:
            lm.append(-lp[0]+lm[0])
            print(lm[0],lp[0])
            del lp[0]
            del lm[0]
        elif lm!=[]:
            print(lm[0],lm[-1])
            del lm[0]
            del lm[-1]
        else:
            o=1
    else:
        if lp!=[] and lm!=[]:
            lp.append(lp[0]-lm[0])
            print(lp[0],lm[0])
            del lp[0]
            del lm[0]
        elif lp!=[]:
            print(lp[0],lp[-1])
            del lp[0]
            del lp[-1]
        else:
            o=1

Submission status: Runtime Error

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

length = len(a_l)
k = 0
for i in range(length):
  if a_l[i] < 0:
    k = i
  else:
    break

b_l = a_l[:k+1]
a_l = a_l[k+1:]
fu = len(b_l)
sei = len(a_l)
ans_l = list()
ans_ll = list()
if sei > fu:
  sa = sei-fu-1
  ans_ll.append(a_l[-1])
  for i in range(fu):
    ans_l.append([b_l[i], a_l[-i-2]])
    ans_ll.append(b_l[i]-a_l[-i-2])
  aa_l = a_l[:sa]
  aa = 0
  for i in range(len(aa_l)-1):
    ans_l.append([aa_l[i], aa_l[i+1]])
    aa = aa_l[i] - aa_l[i+1]
  ans_ll.append(aa)
  ans_ll.sort()
  lent = len(ans_ll)
  for i in range(lent-1):
    ans_l.append([ans_ll[-1], ans_ll[i]])
    ans_ll[-1] = ans_ll[-1]-ans_ll[i]
elif sei < fu:
  sa = fu-sei+1
  if len(a_l) != 0:
    ans_ll.append(a_l[-1])
  b_l = b_l[sa:]
  for i in range(len(b_l)):
    ans_l.append([b_l[i], a_l[-i-2]])
    ans_ll.append(b_l[i]-a_l[-i-2])
  bb_l = b_l[:sa]
  bb_l.reverse()
  aa = 0
  for i in range(len(aa_l)-1):
    ans_l.append([aa_l[i], aa_l[i+1]])
    aa = aa_l[i] - aa_l[i+1]
  ans_ll.append(aa)
  ans_ll.sort()
  lent = len(ans_ll)
  for i in range(lent-1):
    ans_l.append([ans_ll[-1], ans_ll[i]])
    ans_ll[-1] = ans_ll[-1]-ans_ll[i]
else:
  for i in range(sei):
    if i == 0:
      ans_l.append([a_l[-i-1], b_l[i]])
      ans_ll.append(a_l[-i-1]-b_l[i])
    else:
      ans_l.append([b_l[i], a_l[-i-1]])
      ans_ll.append(b_l[i]-a_l[-i-1])
  ans_ll.sort()
  lent = len(ans_ll)  
  for i in range(lent-1):
    ans_l.append([ans_ll[-1], ans_ll[i]])
    ans_ll[-1] = ans_ll[-1]-ans_ll[i]
    
ans_length = len(ans_l)
print(ans_ll[-1])
for i in range(ans_length):
  a = ans_l[i][0]
  b = ans_l[i][1]
  print(a, b)

Submission status: Runtime Error

Solution code:
N = int(input())
# -*- coding: utf-8 -*-
#hq = []
#hq_inv = []#大きいもの
#import heapq
l = list(map(int,input().split()))
l.sort()
import bisect
index = bisect.bisect_right(l, 0)
if index == 0:
    print(sum(l)-l[0])
else:
    print(sum(l[index:]-sum(l[:index-1])))

Submission status: Runtime Error

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

nega = sorted(list(filter(lambda x: x < 0, a)))
posi = sorted(list(filter(lambda x: x >= 0, a)), reverse=True)

selected = []

for i in range(n - 1):
  if len(nega) == 0:
    (x, y) = posi[0], posi[-1]
    posi = posi[1:-1]
    selected.append((x, y))
    nega.append(x - y)
  elif len(posi) == 0:
    (x, y) = nega[0], nega[-1]
    nega = nega[1:-1]
    selected.append((x, y))
    posi.append(x - y)
  else:
    if len(nega) >= len(posi):
      (x, y) = posi.pop(), nega.pop()
      selected.append((x,y))
      posi.append(x - y)
    else:
      (x, y) = nega.pop(), posi.pop()
      selected.append((x, y))
      nega.append(x - y)

if len(nega) == 1:
  print(nega[0])
else:
  print(posi[0])

for (x, y) in selected:
  print(f'{x} {y}')

Submission status: Runtime Error

Solution code:
import sys
n = int(input())
a = list(map(int, input().split()))
iplus =[]
iminus =[]
method =[]
for i in range(n):
    tmp = a[i]
    if tmp >0:
        iplus.append(tmp)
    elif tmp <0:
        iminus.append(tmp)
iplus.sort()
iminus.sort()

while len(iminus) + len(iplus) > 1:
    tmp = iplus[len(iplus) -1] - iminus[0]
    tmp1 =iplus[len(iplus) -1]
    tmp2 = iminus[0]
    del iplus[len(iplus) -1], iminus[0]
    if len(iplus) > len(iminus) and tmp != 0:
        iminus.append(-abs(tmp))
        method.append([tmp2,tmp1])
    else:
        iplus.append(abs(tmp))
        method.append([tmp1,tmp2])

    iplus.sort()
    iminus.sort()

    
print(abs(sum(iplus)) + abs(sum(iminus)))
for i in range(n-1):
    print(method[i][0],method[i][1])

Submission status: Runtime Error

Solution code:
N = int(input())
List = list(map(int,input().split()))
List = sorted(List)
found = False
i = N//2 
while found == False and i < N:
    if List[i]>=0:
        found = True
    else:
        i = i+1

A = List[:i]
B = List[i:]
print(A,B)
a = 0
y = 0
print(sum(B)-sum(A))
for k in range(N - i-1):
    x = B[k]
    if a != 0:
        print(x,y)
    y = x-y
    a += 1
    x = A[k]
    print(x,y)
    y = x-y
x = B[N-i-1]    
print(x,y)
x = x-y
for k in range(N-i-1,i):
    y = A[k]
    print(x,y)
    x = x - y

Submission status: Runtime Error

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

xy = [0]*N-1
idx = 0

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

        xy[idx] = [x,y]

        A[0] = x-y

    else:
        x = A.pop()
        y = A.pop(0)

        xy[idx] = [x,y]

        A.append(x-y)
    
    idx += 1

print(A[0])
for x, y in xy:
    print(x,y)

Submission status: Runtime Error

Solution code:
from heapq import heappop,heappush
n = int(input())
A = sorted(list(map(int,input().split())))
p = 0
P = []
m = 0
M = []
for a in A:
    if a>=0:
        p += 1
        P.append(a)
    else:
        m += 1
        M.append(a)
if m!=0 and p!=0:
    res = 0
    for a in A:
        res += abs(a)
    print(res)
    while p!= 1:
        mm = heappop(M)
        pp = heappop(P)
        print(mm,pp)
        p -= 1
        heappush(M,mm-pp)
    while m != 0:
        mm = heappop(M)
        pp = heappop(P)
        print(pp,mm)
        m -= 1
        heappush(P,pp-mm)
elif m == 0:
    print(sum(P)-min(P)*2)
    mm = heappop(P)
    pp = heappop(P)
    print(mm,pp)
    p -= 2
    m += 1
    heappush(M,mm-pp)
    while p!= 1:
        mm = heappop(M)
        pp = heappop(P)
        print(mm,pp)
        p -= 1
        heappush(M,mm-pp)
    while m != 0:
        mm = heappop(M)
        pp = heappop(P)
        print(pp,mm)
        m -= 1
        heappush(P,pp-mm)
else:
    res = 0
    MMM = -100000000
    for m in M:
        MMM = max(MMM,m)
        res += abs(m)
    print(res+MMM*2)
    M.sort()
    mm = M[-1]
    pp = M[-2]
    print(mm,pp)
    m -= 2
    p += 1
    M = M[:-2]
    heappush(P,mm-pp)
    while p!= 1:
        mm = heappop(M)
        pp = heappop(P)
        print(mm,pp)
        p -= 1
        heappush(M,mm-pp)
    while m != 0:
        mm = heappop(M)
        pp = heappop(P)
        print(pp,mm)
        m -= 1
        if m==0:
            exit()
        heappush(P,pp-mm)

Submission status: Runtime Error

Solution code:
N = int(input())
a = list(map(int, input().split()))
a.sort()
b = a[0] - a[N - 1]
d = a[0]
e = a[N - 1]
if N > 2:
    for i in range(N - 3):
        b = b - a[N - 2 - i] 
    if b > a[1]:
        print(b - a[1])
    else:
        print(a[1] - b)
    print(c)
    for j in range(N - 2):
        print(d, end = ' ')
        print(e)
        d = d - e
        e = a[N - 2 - j]
    if e >= 0:
        print(e, end = ' ')
        print(d, end = ' ')
    else:
        print(d, end = ' ')
        print(e, end = ' ')
else:
    print(a[1] - a[0])
    print(a[1], end = ' ')
    print(a[0], end = ' ')

Submission status: Runtime Error

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

length = len(a_l)
k = 0
for i in range(length):
  if a_l[i] < 0:
    k = i
  else:
    break

b_l = a_l[:k+1]
a_l = a_l[k+1:]
fu = len(b_l)
sei = len(a_l)
ans_l = list()
ans_ll = list()
if sei > fu:
  sa = sei-fu-1
  ans_ll.append(a_l[-1])
  for i in range(fu):
    ans_l.append([b_l[i], a_l[-i-2]])
    ans_ll.append(b_l[i]-a_l[-i-2])
  aa_l = a_l[:sa]
  aa = 0
  for i in range(len(aa_l)-1):
    ans_l.append([aa_l[i], aa_l[i+1]])
    aa = aa_l[i] - aa_l[i+1]
  ans_ll.append(aa)
  ans_ll.sort()
  lent = len(ans_ll)
  for i in range(lent-1):
    ans_l.append([ans_ll[-1], ans_ll[i]])
    ans_ll[-1] = ans_ll[-1]-ans_ll[i]
elif sei < fu:
  sa = fu-sei+1
  if len(a_l) != 0:
    ans_ll.append(a_l[-1])
  b_l = b_l[sa:]
  for i in range(len(b_l)):
    ans_l.append([b_l[i], a_l[-i-2]])
    ans_ll.append(b_l[i]-a_l[-i-2])
  bb_l = b_l[:sa]
  bb_l.reverse()
  aa = 0
  for i in range(len(aa_l)-1):
    ans_l.append([aa_l[i], aa_l[i+1]])
    aa = aa_l[i] - aa_l[i+1]
  ans_ll.append(aa)
  ans_ll.sort()
  lent = len(ans_ll)
  for i in range(lent-1):
    ans_l.append([ans_ll[-1], ans_ll[i]])
    ans_ll[-1] = ans_ll[-1]-ans_ll[i]c
else:
  for i in range(sei):
    if i == 0:
      ans_l.append([a_l[-i-1], b_l[i]])
      ans_ll.append(a_l[-i-1]-b_l[i])
    else:
      ans_l.append([b_l[i], a_l[-i-1]])
      ans_ll.append(b_l[i]-a_l[-i-1])
  ans_ll.sort()
  lent = len(ans_ll)  
  for i in range(lent-1):
    ans_l.append([ans_ll[-1], ans_ll[i]])
    ans_ll[-1] = ans_ll[-1]-ans_ll[i]
    
ans_length = len(ans_l)
print(ans_ll[-1])
for i in range(ans_length):
  a = ans_l[i][0]
  b = ans_l[i][1]
  print(a, b)

Submission status: Runtime Error

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

if N % 2 == 0:
    A_neg = A[:N//2]
    A_pos = A[N//2:]
    M = sum(A_pos) - sum(A_neg)
    print(M)
    print(' '.join(map(str, [A[-1], A[0]])))
    num = A[-1] - A[0]
    for i in range(N-2):
        print(' '.join(map(str, [num, A[i+1]])))

if N % 2 == 1:
    A_neg = A[:N//2]
    A_pos = A[N//2:]
    M = sum(A_pos) - sum(A_neg)
    print(M)
    print(' '.join(map(str, [A[-1], A[0]])))
    num = A[-1] - A[0]
    for i in range(N-2):
        print(' '.join(map(str, [num, A[i+1]])))

Submission status: Runtime Error

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__


def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    a.sort()

    if a[-1] <= 0:
        s = max(a)
        a.remove(s)

        X, Y = [], []
        for _ in range(n - 2):
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        ai = a.pop()
        X.append(s), Y.append(ai)

        print(s - ai)
        for x, y in zip(X, Y):
            print(x, y)
    elif a[0] >= 0:
        s = min(a)
        a.remove(s)

        X, Y = [], []
        for _ in range(n - 2):
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        ai = a.pop()
        X.append(ai), Y.append(s)

        print(ai - s)
        for x, y in zip(X, Y):
            print(x, y)
    else:
        s = min(a)
        a.remove(s)

        X, Y = [], []
        while a[-1] >= 0 and len(a) > 1:
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        a = [s] + a

        s = max(a)
        a.remove(s)

        X, Y = [], []
        while len(a) > 1:
            ai = a.pop()
            X.append(s), Y.append(ai)
            s -= ai

        ai = a.pop()
        X.append(s), Y.append(ai)

        print(s - ai)
        for x, y in zip(X, Y):
            print(x, y)

        ai = a.pop()
        X.append(ai), Y.append(s)

        print(ai - s)
        for x, y in zip(X, Y):
            print(x, y)

# 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: Runtime Error

Solution code:
numbers = input()
numbers = numbers.split(" ")
numbers.pop(0)

order = ""
max_num = ""

def getDiff(list):
    list.sort(reverse = True)
    length = len(list)
    result_list = []
    result_num = ""
    rest = length%2
    list1 = list[0:int((length - rest) /2 + rest)]
    list2 = list[int((length - rest) /2 + rest):]
    print(list1, list2)
    while len(list1) > 0 and len(list2) > 0:
        num1 = list1.pop(0)
        num2 = list2.pop(0)
        result_num += "\n" + num1 + " " + num2
        result_list.append(str(int(num1) - int(num2)))
    if len(list1) > 0:
        result_list.append(list1.pop())
    return result_list, result_num

while len(numbers) > 1:
    numbers, num_set = getDiff(numbers)
    order += num_set

max_num = numbers[0]
result = str(max_num) + order
print(result)

Submission status: Runtime Error

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

p = m = 0

p = len([i for i in li if i >= 0])
m = len([i for i in li if i < 0])

tejun = []

li.sort()
# p と m の数を合わせる
if p == 0:
  while True:
    tejun.append([li[0], li[1]])
    li[0] = li[0] - li[1]
    del li[1]

    if li[0] < 0:
    break
    
if m == 0:
  while True:
    tejun.append([li[-1], li[2]])
    li[-1] = li[-1] - li[-2]
    del li[-2]

    if li[-1] >= 0:
    break

if p > m and m != 0:
  for i in range(1, p-m+1):
    tejun.append([li[0], li[-i]])
    li[0] = li[0] - li[-i]
    
  del li[-(p-m):]
  
elif m > p and p != 0:
  for i in range(m-p):
    tejun.append([li[-1], li[i]])
    li[-1] = li[-1] - li[i]
    
  del li[:m-p]
  
count = 0

while True:
  print(tejun)
  if count % 2 == 0:
    tejun.append([li[-1], li[0]])
    li[-1] = li[-1] - li[0]
    del li[0]
  else:
    tejun.append([li[0], li[-1]])
    li[0] = li[0] - li[-1]
    del li[-1]
  count += 1
  if len(li) == 1:
    break
    
print(li[0])
for i in tejun:
  print(i[0], i[1])

Submission status: Runtime Error

Solution code:
import sys
n = int(input())
a = list(map(int, input().split()))
iplus =[]
iminus =[]
method =[]
for i in range(n):
    tmp = a[i]
    if tmp >0:
        iplus.append(tmp)
    elif tmp <0:
        iminus.append(tmp)
iplus.sort()
iminus.sort()

while len(iminus) + len(iplus) > 1:
    tmp = iplus[len(iplus) -1] - iminus[0]
    tmp1 =iplus[len(iplus) -1]
    tmp2 = iminus[0]
    del iplus[len(iplus) -1], iminus[0]
    if len(iplus) > len(iminus) and tmp != 0:
        iminus.append(-abs(tmp))
        method.append([tmp2,tmp1])
    else:
        iplus.append(abs(tmp))
        method.append([tmp1,tmp2])

    iplus.sort()
    iminus.sort()

    
print(abs(sum(iplus)) + abs(sum(iminus)))
for i in range(n):
    print(method[i][0],method[i][1])

Submission status: Runtime Error

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

tasug=[]
hikug=[]
for i in range(n):
  if a[i]<0:
    hikug.append(a[i])
  else:
    tasug.append(a[i])

if len(hikug)==0:
  tasug.sort()
  ans=sum(tasug)-2*tasug[0]
  print(ans)
  for i in range(len(tasug)-1):
    if i ==0:
      print(tasug[0],tasug[1])
      a=tasug[0]-tasug[i]
    elif i==1:
      continue
    else:
      print(a,tasug[i])
      a=a-tasug[i]
  if not n==2:
    print(tasug[len(tasug)-1],a)
  
  
elif len(tasug)==0:
  hikug.sort()
  ans=-sum(hikug)+2*hikug[n-1]
  print(ans)
  for i in range(n-1):
    if i ==0:
      a=hikug[n-1]

    print(a,hikug[i])
    a=a-hikug[i]

else:
  ans=sum(tasug)-sum(hikug)
  print(ans)
  for i in range(len(tasug)-1):
    if i ==0:
      print(hikug[0],tasug[i])
      a=hikug[0]-tasug[i]
    else:
      print(a,tasug[i])
      a=a-tasug[i]

  print(tasug[len(tasug)-1],a)
  a=tasug[len(tasug)-1]-a

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

Submission status: Runtime Error

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

while True:
    A.sort()
    B = []
    for i in range(len(A)-1):
        B.append(abs(A[i+1]-A[i]))
        
    A.append(A[B.index(max(B))]-A[B.index(max(B))+1])
    C.append([A[B.index(max(B))],A[B.index(max(B))+1]])
    del A[B.index(max(B))+1]
    del A[B.index(max(B))]
    
    if len(A) == 2:
        print(abs(A[0]-A[1]))
        break

for i in C:
    print(i[0],i[1])
print(max(A),min(A))

Submission status: Runtime Error

Solution code:
import numpy as np


N = int(input())

poss, negs = [], []
npos, nneg = 0, 0
for a in input().split():
    ia = int(a)
    if ia < 0:
        negs.append(ia)
        nneg += 1
    else:
        poss.append(ia)
        npos += 1

# import random
# N = 100000
# npos, nneg = 40000, 60000
# poss = [random.randint(1, 1000) for _ in range(npos)]
# negs = [random.randint(-1000, -1) for _ in range(nneg)]

# poss = [0, 0, 2]
# negs = [-4, -5, -9]
# npos, nneg = len(poss), len(negs)
# N = npos + nneg

if N == 2:
    a1, a2 = (poss + negs)
    if a1 < a2:
        print(a2 - a1)
        print(a2, a1)
    else:
        print(a1 - a2)
        print(a1, a2)
    exit(1)

if nneg == 0:
    print(sum(poss) - min(poss) * 2)
    argmin = np.array(poss).argmin()
    minpos = poss.pop(argmin)
    pos = poss.pop()
    print(minpos, pos)
    negs.append(minpos - pos)
    npos -= 2
    nneg += 1
elif npos == 0:
    print(-sum(negs) + max(negs) * 2)
    argmax = np.array(negs).argmax()
    maxneg = negs.pop(argmax)  # -1とか
    neg = negs.pop()  # -5とか
    print(maxneg, neg)
    poss.append(maxneg - neg)
    nneg -= 2
    npos += 1
else:
    print(sum(poss) - sum(negs))

if npos > nneg:
    for _ in range(npos - nneg):
        pos, neg = poss.pop(), negs.pop()
        print(neg, pos)
        negs.append(neg - pos)
elif npos < nneg:
    for _ in range(nneg - npos):
        pos, neg = poss.pop(), negs.pop()
        print(pos, neg)
        poss.append(pos - neg)

for i in range(min(nneg, npos) - 1):
    pos, neg = poss.pop(), negs.pop()
    print(neg, pos)
    negs.append(neg - pos)
    pos, neg = poss.pop(), negs.pop()
    print(pos, neg)
    poss.append(pos - neg)

pos, neg = poss.pop(), negs.pop()
print(pos, neg)

Submission status: Runtime Error

Solution code:
import sys, math, collections, heapq, itertools
from bisect import bisect_left
  
def solve():
    file = sys.stdin.readline #single: int(file()), line: map(int, file().split())
    INF = 10 ** 25
    mod = 7 + 10 ** 9
    N = int(file())
    A = [int(a) for a in file().split()]
    A.sort()
    ans = 0
    out = []
    if N == 2:
        ans = A[1] - A[0]
        out = [A[1], A[0]]
    elif A[N-2] <= 0:
        ans = A[N-1] - A[N-2]
        out.append([A[N-1], A[N-2]])
        for i in range(N-2):
            out.append([ans, A[i]])
            ans -= A[i]
    elif A[1] >= 0:
        ans = A[0] - A[1]
        out.append([A[0], A[1]])
        for i in range(2, N-1):
            out.append([ans, A[i]])
        out.append([A[N-1], ans])
        ans = A[N-1] - ans
    else:
        start = bisect_left(A, 0)
        start -= 1
        ans = A[start] - A[start + 1]
        out.append([A[start], A[start + 1]])
        if start + 2 < N - 1:
            for i in range(start + 2, N - 1):
                out.append([ans, A[i]])
                ans -= A[i]
        out.append([A[N-1], ans])
        ans = A[N-1] - ans
        if start > 0:
            for i in range(start):
                out.append([ans, A[i]])
                ans -= A[i]

    print(ans)
    for k in out:
        print(" ".join(map(str, k)))

    return 0
  
if __name__ == "__main__":
    solve()