Problem:


Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0



Sample input:
3
1 -1 2


Sample output:
4
-1 1
2 -2

Submission status: Accepted

Solution code:
N = int(input())

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

A_sorted = sorted(A_list)

pos_count = len([a for a in A_sorted if a >= 0])
neg_count = len([a for a in A_sorted if a < 0])

if pos_count == 0:
    pos_count = 1
    neg_count = N - 1
if neg_count == 0:
    pos_count = N - 1
    neg_count = 1

output_list = [0] * (N - 1)
count = 0
for q in range(neg_count, N - 1):
    output_list[count] = [A_sorted[0], A_sorted[q]]
    count += 1
    A_sorted[0] -= A_sorted[q]


for i in range(neg_count):
    output_list[count] = [A_sorted[N - 1], A_sorted[i]]
    count += 1
    A_sorted[N - 1] -= A_sorted[i]

print(A_sorted[N - 1])
for item in output_list:
    print(item[0], item[1])

Submission status: Accepted

Solution code:
n=int(input())
a=[]
r=[]
for i in input().split():
  a.append(int(i))
a.sort()
t=a.pop(-1)
b=a.pop(0)
for i in a:
  if i>=0:
    r.append([b,i])
    b=b-i
  else:
    r.append([t,i])
    t=t-i
print(t-b)
r.append([t,b])
for i in r:
  print(i[0],i[1])

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
final_list = []
plus = sum(x >= 0 for x in A)

def pop(length, flag):
  val = A[flag]
  A.pop(flag)
  for i in range(length):
    next_add = A[-1 - flag]
    final_list.append((val, next_add))
    val = val - next_add
    A.pop(-1 - flag)
  return val

if plus == N: #全部正の数
  ans = pop(N - 2, 0)
  final_list.append((max(ans, A[0]), min(ans, A[0])))
  ans = abs(ans - A[0])
elif plus == 0: #全部負の数
  ans = pop(N - 2, -1)
  final_list.append((max(ans, A[0]), min(ans, A[0])))
  ans = abs(ans - A[0])
else:
  ans_neg = pop(plus - 1, 0)
  ans_pos = pop(N - plus - 1, -1)
  final_list.append((ans_pos, ans_neg))
  ans = ans_pos - ans_neg
  


print(ans)
for i in range(len(final_list)):
  print(final_list[i][0], " ", final_list[i][1])

Submission status: Accepted

Solution code:
from collections import deque

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

A_pos = [x for x in A if x >= 0]  # プラスとして使うもの
A_minus = [x for x in A if x < 0]  # マイナスとして使うもの
if len(A_pos) == 0:
    max_tmp = A_minus[-1]
    A_minus = A_minus[:-1]
    A_pos.append(max_tmp)

if len(A_minus) == 0:
    min_tmp = A_pos[0]
    A_pos = A_pos[1:]
    A_minus.append(min_tmp)

A_pos = deque(A_pos)
A_minus = deque(A_minus)

# calc steps
while True:
    if len(A_pos) == 1 and len(A_minus) == 1:
        break
    if len(A_pos) == 1:
        pos = A_pos.pop()
        minus = A_minus.pop()
        steps.append((pos, minus))
        pos -= minus
        A_pos.append(pos)
        continue
    if len(A_minus) == 1:
        # Then len(A_pos) > 1
        pos = A_pos.pop()
        minus = A_minus.pop()
        steps.append((minus, pos))
        minus -= pos
        A_minus.append(minus)
        continue
    pos = A_pos.pop()
    minus = A_minus.pop()
    steps.append((pos, minus))
    pos -= minus
    A_pos.append(pos)

pos = A_pos.pop()
minus = A_minus.pop()

steps.append((pos, minus))
print(pos - minus)
for x, y in steps:
    print('{} {}'.format(x, y))

Submission status: Accepted

Solution code:

# -*- coding: utf-8 -*-
# @Date    : 2019-06-15 20:23:26
# @Author  : raj lath (oorja.halt@gmail.com)
# @Link    : link
# @Version : 1.0.0

import sys
sys.setrecursionlimit(10**5+1)

inf     =  int(10 ** 20)
max_val =  inf
min_val = -inf

RW  = lambda : sys.stdin.readline().strip()
RI  = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]


nb_elem = RI()
elements = sorted(RMI())
mins = elements[0]
maxs = elements[-1]
ans = []
for e in elements[1:-1]:
    if e > 0:
        ans.append([mins, e])
        mins -= e
    else:
        ans.append([maxs, e])
        maxs -= e
ans.append([maxs, mins])
print(maxs - mins)
for i in ans:
    print(*i)

Submission status: Accepted

Solution code:
n = int(input())
s = n % 2
a = list(map(int, input().split()))
a.sort()
mi = a[0]
ma = a[n - 1]
l = []
for i in range(1, n - 1):
    if a[i] < 0:
        l.append((ma, a[i]))
        ma -= a[i]
    else:
        l.append((mi, a[i]))
        mi -= a[i]
l.append((ma, mi))
print(ma - mi)
for x, y in l:
    print(x, y)

Submission status: Accepted

Solution code:
N = int(input())
a = sorted(list(map(int, input().split())))
nyu = []
ma = a[-1]
mi = a[0]
i=0
while i!=N-2:
    if a[i+1]>=0:
        nyu.append([mi, a[i+1]])
        mi -= a[i+1]
    else:
        nyu.append([ma, a[i+1]])
        ma -= a[i+1]
    i += 1
nyu.append([ma, mi])
print(nyu[N-2][0]-nyu[N-2][1])
for i in range(N-1):
    print(nyu[i][0], nyu[i][1])

Submission status: Accepted

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

ans = []
res = 0
m = a[0]  # 最後に引く側
p = a[-1]  # 最後に足す側
for aa in a[1:N - 1]:
    if aa < 0:
        res -= aa
        ans.append((p, aa))
        p -= aa
    else:
        res += aa
        ans.append((m, aa))
        m -= aa
ans.append((p, m))

res += a[-1] - a[0]
print(res)
for aa in ans:
    print(*aa)

Submission status: Accepted

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

mn = A[0]
mx = A[-1]
if N ==2:
    print(A[1] - A[0])
    print(A[1],A[0])
    sys.exit()
ope = []
for a in A[1:-1]:
    if a <=0:
        ope.append([mx, a])
        mx -= a
    else:
        ope.append([mn, a])
        mn -= a
ope.append([mx,mn])
print(mx-mn)
for o in ope:
    print(o[0],o[1])

Submission status: Accepted

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

a.sort()

posi = [a[-1]]
nega = [a[0]]

for n in a[1:-1]:
  if n < 0:
    nega.append(n)
  else:
    posi.append(n)

selected = []
ans = nega[0]

for n in posi[1:]:
  (x, y) = ans, n
  ans = x - y
  selected.append((x, y))

nega.append(ans)

ans = posi[0]
for n in nega[1:]:
  (x, y) = ans, n
  ans = x - y
  selected.append((x, y))

print(ans)

for (x, y) in selected:
  print(str(x) + ' ' + str(y))

Submission status: Accepted

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

ans = lst[n-1] - lst[0]
for i in range(1,n-1):
    ans += abs(lst[i])

print(ans)

for i in range(1,n-1):
    if lst[i] >= 0:
        print("%s %d" % (lst[0],lst[i]))
        lst[0] = lst[0] - lst[i]
    else:
        print("%s %d" % (lst[n-1],lst[i]))
        lst[n-1] = lst[n-1] - lst[i]
        

print("%s %d" % (lst[n-1],lst[0]))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
ans = 0
hoge = sum(A)
p = 0
for i in range(N-1):
    hoge -= A[i]*2
    if hoge > ans:
        ans = hoge
        p = i
print(ans)
hoge = A[0]
for i in range(p+1,N-1):
    print(hoge,A[i])
    hoge -= A[i]
print(A[N-1],hoge)
hoge = A[N-1] - hoge
for i in range(1,p+1):
    print(hoge,A[i])
    hoge -= A[i]

Submission status: Accepted

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

A = sorted(A)
plus = []
minus = []

for i in range(N):
    if i == 0:
        minus.append(A[i])
    elif i == N-1:
        plus.append(A[i])
    else:
        if A[i] > 0:
            plus.append(A[i])
        else:
            minus.append(A[i])

print(sum(plus)-sum(minus))
tmp = minus[0]
for i in range(len(plus)-1):
    print(tmp,plus[i])
    tmp -= plus[i]

minus[0] = tmp
tmp2 = plus[-1]
for i in range(len(minus)):
    print(tmp2,minus[i])
    tmp2 -= minus[i]

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)

N = None
As = None
used_plus = 0
used_minus = 0

def make_leaf():
    return [True, None, None, None]

def make_branch(left, right):
    return [False, None, left, right]

def count(nminus):
    global N, As
    res = 0
    for i in range(N):
        if i < nminus:
            res -= As[i]
        else:
            res += As[i]
    return res

def make_tree(a, b):
  if a + b == 1:
      if a == 1:
        return make_leaf()
      else:
          raise Exception("tukurenai")
  else:
      x = 1
      z = 1
      y = b - z
      w = a - x
      return make_branch(make_tree(x, y), make_tree(z, w))


def f(node, minus):
    global N, As, used_plus, used_minus
    [leaf, value, left, right] = node
    if leaf:
        if minus:
            node[1] = As[used_minus]
            used_minus += 1
        else:
            node[1] = As[N - 1 - used_plus]
            used_plus += 1
    else:
        f(left, minus)
        f(right, not minus)

def g(node):
    [leaf, value, left, right] = node
    if leaf:
        return value;
    else:
        x = g(left);
        y = g(right);
        print(str(x) + " " + str(y))
        return x - y

def show(nminus):
    node = make_tree(N - nminus, nminus)
    f(node, False)
    g(node)

def main():
    global N, As
    N = int(input())
    As = list(map(int,input().split()))
    As.sort()
    best = 0
    for i in range(N):
        if As[i] < 0: best = i
    m = -1
    argmax = 0
    for i in range(-1, 2):
        j = min(max(best + i, 1), N - 1)
        c = count(j)
        if c > m:
            m = c
            argmax = j
    print(m)
    show(argmax)

main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
minus = len([i for i in a if i < 0])
if minus == 0:
  minus = 1
elif minus == len(a):
  minus = len(a)-1
  
print(sum(a[minus:])- sum(a[:minus]))
for e in a[minus:-1]:
  print(str(a[0])+" "+str(e))
  a[0] -= e
for e in a[:minus]:
  print(str(a[-1])+" "+str(e))
  a[-1] -= e

Submission status: Accepted

Solution code:
N = int( input())
A = list( map( int, input().split()))
A.sort(reverse = True)
plus = 0
zero = 0
for i in range(N):
    if A[i] > 0:
        plus += 1
    elif A[i] == 0:
        zero += 1
minus = N - plus - zero
if plus + zero== N:
    print(sum(A)-A[-1]*2)
    now = A[-1]
    for i in range(N-2):
        print(now, A[i])
        now -= A[i]
    print(A[N-2], now)
elif minus + zero== N:
    print(A[0]*2 - sum(A))
    now = A[0]
    for i in range(1,N):
        print(now, A[i])
        now -= A[i]
elif plus+zero == 1:
    print( sum( list( map( abs, A))))
    now = A[0]
    for i in range(1,N):
        print(now, A[i])
        now -= A[i]
else:
    print( sum( list( map( abs, A))))
    now = A[N-1]
    k = N-1
    for i in range(1,N-1):
        if A[i] <= 0:
            k = i
            break
        print(now, A[i])
        now -= A[i]
    print(A[0], now)
    now = A[0] - now
    for i in range(k,N-1):
        if A[i] > 0:
            pass
        print(now, A[i])
        now -= A[i]

Submission status: Accepted

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]]]
    else:
        plus = bisect_left(A, 0)
        if plus == 0:
            ans = A[0]
            for i in range(1, N-1):
                out.append([ans, A[i]])
                ans -= A[i]
            out.append([A[N-1], ans])
            ans = A[N-1] - ans
        elif plus < N:
            ans = A[0]
            for i in range(plus, N - 1):
                out.append([ans, A[i]])
                ans -= A[i]
            out.append([A[N-1], ans])
            ans = A[N-1] - ans
            for i in range(1, plus):
                out.append([ans, A[i]])
                ans -= A[i]
        else:
            ans = A[N-1]
            for i in range(N-1):
                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()

Submission status: Accepted

Solution code:
import sys

N=input()
A=map(int, sys.stdin.readline().split())
A.sort()
min_A=A[0]
max_A=A[-1]

L=[]
for i in range(1,N-1):
	v=A[i]
	if v<0:
		L.append( (max_A, v) )
		max_A-=v
	else:
		L.append( (min_A, v) )
		min_A-=v
else:
	L.append( (max_A,min_A) )
	print max_A-min_A
	for x,y in L:
		print x,y

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    A.sort()
    M = A.pop()
    m = A.pop(0)

    ans = []
    while A:
        a = A.pop()
        if a < 0:
            ans.append((M, a))
            M -= a
        else:
            ans.append((m, a))
            m -= a

    print(M-m)
    for x, y in ans:
        print(x, y)
    print(M, m)


def main():
    N = read_int()
    A = read_int_n()
    (slv(N, A))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

plus=[]
minus=[]

if min(A)>=0:
    tmp=min(A)
    print(sum(A)-tmp*2)
    if len(A)==2:
        print(max(A),min(A))
        sys.exit()
    tmpind=A.index(tmp)
    if tmpind==len(A)-1:
        tmpind=0
        aa=A[0]
        A[0]=A[-1]
        A[-1]=aa
    for i in range(len(A)-1):
        if i==tmpind:continue
        print(tmp,A[i])
        tmp-=A[i]
    print(A[-1],tmp)
    
elif max(A)<=0:
    tmp=max(A)
    print(-(sum(A)-tmp*2))
    if len(A)==2:
        print(max(A),min(A))
        sys.exit()
    tmpind=A.index(tmp)
    if tmpind==len(A)-1:
        tmpind=0
        aa=A[0]
        A[0]=A[-1]
        A[-1]=aa
    for i in range(len(A)-1):
        if i==tmpind:continue
        print(tmp,A[i])
        tmp-=A[i]
    print(tmp,A[-1])
    
else:
    print(sum(map(abs,A)))
    for i in range(len(A)):
        if A[i]>0:
            plus.append(A[i])
        else:
            minus.append(A[i])
    if len(plus)==1 and len(minus)==1:
        print(plus[0],minus[0])
    elif len(minus)==1:
        tmp=minus[0]
        for i in range(len(plus)-1):
            print(tmp,plus[i])
            tmp-=plus[i]
        print(plus[-1],tmp)
    else:
        for i in range(1,len(minus)):
            print(plus[-1],minus[i])
            plus[-1]-=minus[i]
        tmp=minus[0]
        for i in range(len(plus)-1):
            print(tmp,plus[i])
            tmp-=plus[i]
        print(plus[-1],tmp)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
min=a[0]
max=a[-1]
ans=[]
for a in a[1:-1]:
    if a>0:
        ans.append([min,a])
        min-=a
    else:
        ans.append([max,a])
        max-=a
ans.append([max,min])
print(max-min)
for x,y in ans:
    print(x,y)

Submission status: Accepted

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

def readInts():
  return [int(s) for s in input().split(" ")]

def main():
  N = readInts()[0]
  A = readInts()

  A.sort()
  numMinus = 1
  for i in range(1, N):
    if A[i] < 0:
      numMinus += 1
    else:
      break

  if numMinus == N:
    numMinus = N - 1

  seq = []
  for i in range(numMinus, N-1):
    seq.append((A[0], A[i]))
    A[0] = A[0] - A[i]
  for i in range(numMinus):
    seq.append((A[N-1], A[i]))
    A[N-1] = A[N-1] - A[i]

  print(A[N-1])
  for x, y in seq:
    print("{} {}".format(x, y))

if __name__ == "__main__":
  main()

Submission status: Accepted

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

BB = A[:]

BB_P = []
BB_M = []


for b in BB:
    if b < 0:
        BB_M.append(b)
    else:
        BB_P.append(b)

        
ope = []
if not BB_M:
    BB_P = sorted(BB_P)
    p = BB_P[-1]
    m = BB_P[0]
    for b in BB_P[1:-1]:
        ope.append((m,b))
        m = m-b
    ope.append((p,m))
    ans = p - m
elif not BB_P:
    BB_M = sorted(BB_M)
    p = BB_M[-1]
    for b in BB_M[:-1]:
        ope.append((p, b))
        p = p-b
    ans = p
else:
    p = BB_P.pop()
    m = BB_M.pop()
    for b in BB_P:
        ope.append((m ,b))
        m = m-b
    for b in BB_M:
        ope.append((p ,b))
        p = p-b
    ope.append((p,m))
    ans = p-m
    
print(ans)
for x,y in ope:
    print(x, y)

Submission status: Accepted

Solution code:
def plus(pl):
    if len(pl) == 1:
        return pl[0]
    pl.sort()
    tmp = pl.pop(0)
    while len(pl) > 1:
        tmp2 = pl.pop(0)
        print(tmp, tmp2)
        tmp -= tmp2
    print(pl[0], tmp)
    return pl[0]-tmp


def minas(mi):
    if len(mi) == 1:
        return mi[0]
    mi.sort()
    tmp = mi.pop()
    while len(mi) > 1:
        tmp2 = mi.pop()
        print(tmp, tmp2)
        tmp -= tmp2
    print(tmp, mi[0])
    return tmp-mi[0]


n = int(input())

mi = []
pl = []

for i in [int(j) for j in input().split()]:
    if i < 0:
        mi.append(i)
    else:
        pl.append(i)

if len(pl) == 0:
    print(2*max(mi)-sum(mi))
    minas(mi)
elif len(mi) == 0:
    print(sum(pl)-2*min(pl))
    plus(pl)
else:
    print(abs(sum(mi))+sum(pl))
    mi.sort()
    pl.sort(reverse=True)
    while len(pl) > 1:
        tmp = pl.pop()
        print(mi[0], tmp)
        mi[0] -= tmp

    while len(mi) > 1:
        tmp = mi.pop()
        print(pl[0], tmp)
        pl[0] -= tmp

    print(pl[0], mi[0])

Submission status: Accepted

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]
if len(b_l) != 0:
  min_b = b_l[0]
a_l = a_l[k+1:]
if len(a_l) != 0:
  max_a = a_l[-1]
fu = len(b_l)
sei = len(a_l)
ans_l = list()
ans_n_l = list()
if len(b_l) != 0:
  if len(a_l) != 0:
    for i in range(1, fu):
      ans_l.append([max_a, b_l[i]])
      max_a -= b_l[i]
    for i in range(sei-1):
      ans_l.append([min_b, a_l[i]])
      min_b -= a_l[i]
    
    ans_l.append([max_a, min_b])
    max_a -= min_b
  else:
    max_a = b_l[-1]
    for i in range(1, fu-1):
      ans_l.append([max_a, b_l[i]])
      max_a -= b_l[i]
    ans_l.append([max_a, min_b])
    max_a -= min_b
else:
  min_b = a_l[0]
  for i in range(1, sei-1):
    ans_l.append([min_b, a_l[i]])
    min_b -= a_l[i]
  ans_l.append([max_a, min_b])
  max_a -= min_b
  
print(max_a)
for i in ans_l:
  print(i[0], i[1])

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
pos, neg = [], []
for num in a:
    if num >= 0:
        pos.append(num)
    else:
        neg.append(num)

def maximizeNeg():
    cur = neg[0]
    for i in range(1, len(neg)):
        ret.append((cur, neg[i]))
        cur -= neg[i]
    return cur

def maximizePos():
    cur = pos[0]
    for i in range(1, len(pos) - 1):
        ret.append((cur, pos[i]))
        cur -= pos[i]
    ret.append((pos[-1], cur))
    cur = pos[-1] - cur
    return cur

pos.sort()
neg.sort(reverse=True)
ret = []
if not neg:
    cur = maximizePos()
elif not pos:
    cur = maximizeNeg()
else:
    curNeg = neg[-1]
    for i in range(len(pos) - 1):
        ret.append((curNeg, pos[i]))
        curNeg -= pos[i]
    curPos = pos[-1]
    for i in range(len(neg) - 1):
        ret.append((curPos, neg[i]))
        curPos -= neg[i]
    ret.append((curPos, curNeg))
    cur = curPos - curNeg

print(cur)
print('\n'.join('%d %d' % (xy[0], xy[1]) for xy in ret))

Submission status: Accepted

Solution code:
#c.py
n = int(input())
lis = list(map(int,input().split()))
lis.sort()
m = lis[0]
M = lis[-1]
ans_lis = []

for now in lis[1:-1]:
    if now > 0:
        ans_lis.append([m,now])
        m -= now
    else:
        ans_lis.append([M,now])
        M -= now
ans_lis.append([M,m])
print(M-m)
for x in ans_lis:
    print(x[0],x[1])

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
    return list(map(int,input().split()))
def m():
    return map(int,input().split())
def onem():
    return int(input())
def s(x):
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa == x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x):
    return " ".join(map(str,x))

n = onem()

a = l()
a.sort()
a = cl.deque(a)
aa = []
co = 0
up = a.pop()
do = a.popleft()

for i in range(len(a)):
    if a[i] >= 0:
        aa.append([do,a[i]])
        do -= a[i]
    else:
        aa.append([up,a[i]])
        up -= a[i]    
aa.append([up,do])
print(up-do)
for i in range(n-1):
    print(jo(aa[i]))

Submission status: Accepted

Solution code:
import bisect
N = int(input())
H = list(map(int, input().split()))
H.sort()
negative_count = bisect.bisect_left(H, 0)
positive_count = N - negative_count

def f():
    # answer
    ans = ""

    if N == 2:
        return "{0} {1}\n".format(H[-1], H[0]), H[-1] - H[0]

    if positive_count == 0:
        ans += "{0} {1}\n".format(H[-1], H[0])
        sum_ans = H[-1] - H[0]
        for i in range(1, N - 1):
            v = H[i]
            ans += "{0} {1}\n".format(sum_ans, v)
            sum_ans = sum_ans - v
        return ans, sum_ans

    if negative_count == 0:
        ans += "{1} {0}\n".format(H[-1], H[0])
        sum_ans = - H[-1] + H[0]

        for i in range(1, N - 2):
            v = H[negative_count + i]
            ans += "{0} {1}\n".format(sum_ans, v)
            sum_ans = sum_ans - v

        v = H[-2]
        ans += "{1} {0}\n".format(sum_ans, v)
        sum_ans = v - sum_ans
        return ans, sum_ans


    if positive_count == 1:
        ans += "{0} {1}\n".format(H[-1], H[0])
        sum_ans = H[-1] - H[0]
    else:
        ans += "{1} {0}\n".format(H[-1], H[0])
        sum_ans = - H[-1] + H[0]

        for i in range(positive_count - 2):
            v = H[negative_count + i]
            ans += "{0} {1}\n".format(sum_ans, v)
            sum_ans = sum_ans - v

        v = H[-2]
        ans += "{1} {0}\n".format(sum_ans, v)
        sum_ans = v - sum_ans

    for i in range(1, negative_count):
        v = H[i]
        ans += "{0} {1}\n".format(sum_ans, v)
        sum_ans = sum_ans - v

    return ans, sum_ans


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

Submission status: Accepted

Solution code:
#coding:utf-8
N = int(input())
A = sorted(list(map(int, input().split())))
mn = A[0]
mx = A[-1]
ls_xy = []
for a in A[1:-1]:
    if a > 0:
        ls_xy.append([mn,a])
        mn -= a
    else:
        ls_xy.append([mx,a])
        mx -= a
ls_xy.append([mx,mn])
print (mx -mn)
[print (x,y) for x,y in ls_xy]

Submission status: Accepted

Solution code:
import heapq
N = int(input())
A = [int(item) for item in input().split()]
# N = 10**5
# A = [item for item in range(N)]
A.sort()
M = A.pop()
heapq.heapify(A)
m = heapq.heappop(A)
res = []
while A:
  a = heapq.heappop(A)
  if a < 0:
    res.append((M, a))
    M -= a
  else:
    res.append((m, a))
    m -= a
print(M-m)
for x, y in res:
  print(x, y)
print(M, m)

Submission status: Accepted

Solution code:
def simulateBoard(posNums, negNums):
  P, N = len(posNums), len(negNums)
  out_str = ""
  
  if P == 0 and N == 2:
    num1 = max(negNums)
    num2 = min(negNums)
    print(num1 - num2)
    print(num1, ' ', num2)
  elif N==0 and P==2:
    num1, num2 = max(posNums), min(posNums)
    print(num1 - num2)
    print(num1, ' ', num2)
  elif P == 0:
    negNums.sort(reverse=True)
    
    num1 = negNums[0]
    num2 = negNums.pop()
    
    last_pos = num1 - num2
    negNums = negNums[1:]
    print(abs(sum(negNums)) + last_pos)
    print(num1, ' ', num2) 
    last_neg = negNums.pop() 
    
    while len(negNums) != 0:
      cur_neg = negNums.pop()
      cur_diff = last_pos - cur_neg
      print(last_pos, ' ', cur_neg, ' ')
      last_pos = cur_diff
   	
    cur_diff = last_pos - last_neg
    print(last_pos, ' ', last_neg, ' ')
    
  
  elif N == 0:
    posNums.sort()
    
    num1 = posNums[0]
    num2 = posNums.pop()
    
    last_neg = num1 - num2
    posNums = posNums[1:]
    print(abs(last_neg) + sum(posNums))
    print(num1, ' ', num2)
    last_pos = posNums.pop()

    while len(posNums) != 0:
      cur_pos = posNums.pop()
      cur_diff = last_neg - cur_pos
      print(last_neg, ' ', cur_pos, ' ')
      last_neg = cur_diff
   	
    cur_diff = last_pos - last_neg
    print(last_pos, ' ', last_neg, ' ')
    
    
    
  
  #if N == 0:
    #last_neg = negNums.pop()
    
    #while len(negNums) != 0:
      #cur_neg = negNums.pop()
      #cur_diff = last_pos - cur_neg
      #print(last_pos, ' ', cur_neg, ' ')
      #last_pos = cur_diff
    
  
  elif P>=1 and N>=1:
    print(abs(sum(negNums)) + sum(posNums)) 
    
    last_pos = posNums.pop()
    last_neg = negNums.pop()
    
    while len(negNums) != 0:
      cur_neg = negNums.pop()
      cur_diff = last_pos - cur_neg
      print(last_pos, ' ', cur_neg, ' ')
      last_pos = cur_diff
    
    while len(posNums) != 0:
      cur_pos = posNums.pop()
      cur_diff = last_neg - cur_pos
      print(last_neg, ' ', cur_pos, ' ')
      last_neg = cur_diff
   	
    cur_diff = last_pos - last_neg
    print(last_pos, ' ', last_neg, ' ')

N = int(input())
nums = input().split()
#print(nums)
nums = [int(i) for i in nums]
pos_nums = []
neg_nums = []

for num in nums:
  if num >= 0: pos_nums.append(num)
  else: neg_nums.append(num)
    
simulateBoard(pos_nums, neg_nums)

Submission status: Accepted

Solution code:
N = int(input())
A = sorted([int(x) for x in input().split()])
ans = []

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

elif A[0] >= 0:
    print(sum(A[1:])-A[0])
    a = A[0]
    for i in range(1,N-1):
        print(a,A[i])
        a -= A[i]
    print(A[N-1],a)

else:
    i = 0
    while A[i] < 0:
        i += 1
    print(sum(A[i:]) - sum(A[:i]))
    a,b = A[i-1],A[i]

    if i != N-1:
        for j in range(N-i-1):
            print(a,A[i+j+1])
            a -= A[i+j+1]
    if i != 1:
        for j in range(i-1):
            print(b,A[j])
            b -= A[j]

    print(b,a)

Submission status: Accepted

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

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

n = A.pop()

for i in range(N-1):
    a = A.pop()
    if a > 0:
        xy[idx] = [A[0], a]
        A[0] -= a
    else:
        xy[idx] = [n, a]
        n -= a
        idx += 1
        for j in A:
            xy[idx] = [n, j]
            n -= j
            idx += 1
        break

    idx += 1

print(n)
for x, y in xy:
    print(x,y)

Submission status: Accepted

Solution code:
n = int(input())
alist = list(map(int,input().split()))
ans = []

if len(alist) == 2:
    alist.sort(reverse = True)
    print(alist[0]-alist[1])
    print(' '.join(map(str,alist)))
else:
    plus =[w for w in alist if w>=0]
    minus =[x for x in alist if x<0]
    if minus == []:
        plus.sort()
        for y in range(len(plus)-2):
            ans.append(' '.join(map(str,plus[y:y+2])))
            plus[y+1] = plus[y]-plus[y+1]
        pplus = plus[::-1]
        ans.append(' '.join(map(str,pplus[0:2])))
        print(pplus[0]-pplus[1])
        for y in ans:
            print(y)
    elif plus == []:
        minus.sort(reverse = True)
        for y in range(len(minus)-1):
            ans.append(' '.join(map(str,minus[y:y+2])))
            minus[y+1] = minus[y]-minus[y+1]
        print(minus[-1])
        for y in ans:
            print(y)
    else:
        for z in range(len(plus)-1):
            ans.append(' '.join(map(str,[minus[0],plus[z]])))
            minus[0] = minus[0]-plus[z]
        for q in minus:
            ans.append(' '.join(map(str,[plus[-1],q])))
            plus[-1] = plus[-1]-q
        print(plus[-1])
        for t in ans:
            print(t)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
a_2 = [abs(a[i]) for i in range(n)]
a.sort()

if a[0] >= 0:
    print([sum(a_2) -2, sum(a_2)][a[0] == 0])
    aa = a[0]
    for i in range(n-1):
        if i == 0:
            print(aa, a[i + 1])
            aa = aa - a[i + 1]
        elif i == n - 2:
            print(a[i + 1], aa)
        else:
            print(aa, a[i+1])
            aa = aa - a[i + 1]

elif a[-1] <= 0:

    print([sum(a_2) -2, sum(a_2)][a[-1] == 0])
    a.reverse()
    if a[-1] == 0:
        a = [a[-1]] + a[0:]
    aa = a[0]
    for i in range(n-1):
        if i == 0:
            print(aa, a[i + 1])
            aa = aa - a[i + 1]
        elif i == n - 2:
            print(aa, a[i + 1])
        else:
            print(aa, a[i+1])
            aa = aa - a[i + 1]

else:
    print(sum(a_2))
    minus = []
    plus = []
    for i in range(n):
        if a[i] < 0:
            minus.append(a[i])
        else:
            plus.append(a[i])
    minus2 = minus.pop()
    plus2 = plus.pop()
    for i in range(len(minus)):
        print(plus2 ,minus[i])
        plus2 -= minus[i]
    for i in range(len(plus)):
        print(minus2, plus[i])
        minus2 -= plus[i]
    print(plus2, minus2)