Problem:


Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

Note that the answer may not fit into a 32-bit integer.



Sample input:
3
10 10
20 20
30 30


Sample output:
20

Submission status: Accepted

Solution code:
n = int(input())
a = []
b = []
for i in range(n):
    t1,t2 = map(int,input().split())
    a.append(t1)
    b.append(t2)
wa = []
for i in range(n):
    wa.append(a[i] + b[i])
c = zip(wa,a,b)
c = sorted(c, reverse = True)
wa, a, b = zip(*c)
ans = 0
flg = 0
for i in range(n):
    if flg == 0:
        ans +=a[i]
        flg = 1
    else:
        ans -=b[i]
        flg = 0
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
AB = [tuple(map(int, input().split())) for _ in range(n)]
AB.sort(key = lambda x : x[0] + x[1], reverse = 1)
ans = 0
for i in range(n):
  a, b = AB[i]
  if i & 1:
    ans -= b
  else:
    ans += a
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    A = []
    for _ in range(n):
        a, b = list(map(int, input().split()))
        A.append([a, b, a + b])
    A.sort(key = lambda x: x[2], reverse = True)
    ans = 0
    for i, a in enumerate(A):
        if i % 2 == 0:
            ans += a[2]
        ans -= a[1]
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input():  return sys.stdin.readline().rstrip()
    def ii():     return int(input())
    def isp():    return input().split()
    def mi():     return map(int, input().split())
    def mi_0():   return map(lambda x: int(x)-1, input().split())
    def lmi():    return list(map(int, input().split()))
    def lmi_0():  return list(map(lambda x: int(x)-1, input().split()))
    def li():     return list(input())
    def debug(x): print(x, file=sys.stderr)
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)
    
    
    n = ii()
    L = [lmi() for _ in range(n)]
    L.sort(key=lambda x: x[0] + x[1])
    
    turn = True
    takahashi, aoki = 0, 0
    while L:
        a, b = L.pop()
        if turn:
            takahashi += a
        else:
            aoki += b
        turn = not turn
    
    print(takahashi - aoki)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    N = int(input())
    C = [None] * N
    ans = 0
    for i in range(N):
        a, b = map(int, input().split())
        C[i] = a+b
        ans -= b
    C.sort(reverse=True)
    print(ans + sum(C[::2]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
point = [0] * n
total_b = 0
for i in range(n):
    a, b = map(int, input().split())
    point[i] = a + b
    total_b += b

point.sort(reverse = True)

sum_t = 0
for i in range(n):
    if i % 2 == 0:
        sum_t += point[i]

print(sum_t - total_b)

Submission status: Accepted

Solution code:
n = int(input())
AB = [tuple(int(x) for x in input().split()) for _ in range(n)]
C = sorted(AB, key=lambda x: x[0] + x[1], reverse=True)
print(sum(a for a, b in C[::2]) - sum(b for a, b in C[1::2]))

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():
    N = in_n()
    ab = []

    for i in range(N):
        a, b = in_nn()
        ab.append((a + b, a, b))

    ab.sort(reverse=True)

    taka = 0
    for i in range(0, N, 2):
        taka += ab[i][1]
    aoki = 0
    for i in range(1, N, 2):
        aoki += ab[i][2]

    ans = taka - aoki
    # print(ab)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import fractions
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
import collections
from collections import Counter
from collections import deque
import pprint
import itertools

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr


# a^n
def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod


# n*(n-1)*...*(l+1)*l
def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a


inf = 10 ** 18
mod = 10 ** 9 + 7

n = ir()
ab = [lr() for i in range(n)]
ab.sort(key = lambda x:x[0]+x[1], reverse=True)
ans = 0
for i in range(n):
    if i%2 == 0:
        ans+=ab[i][0]
    else:
        ans-=ab[i][1]
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ab = [list(map(int,input().split())) for _ in range(n)]

sum_a = 0
sum_ab = []
for a, b in ab:
    sum_a += a
    sum_ab.append(a + b)

sum_ab.sort(reverse=True)
for i in range(1, n, 2):
    sum_a -= sum_ab[i]
print(sum_a)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    L=[[0,0,0]for _ in range(N)]
    for i in range(N):
        a,b=MI()
        L[i]=[a+b,a,b]
        
    L.sort(reverse=True)
    
    a=0
    b=0
    for i in range(N):
        if i%2==0:
            a+=L[i][1]
        else:
            b+=L[i][2]
            
    print(a-b)

main()

Submission status: Accepted

Solution code:
n=int(input())
a=[]
b=[]
for i in range(n):
    ai,bi=map(int,input().split())
    a.append(ai)
    b.append(bi)

ab=[a[i]+b[i] for i in range(n)]

ab.sort(reverse=True)
asum=sum(ab[::2])
print(asum-sum(b))

Submission status: Accepted

Solution code:
n=int(input())
ab=[list(map(int,input().split()))for i in range(n)]
ab.sort(key=lambda x:x[0]+x[1],reverse=True)
b=[i[1]for i in ab]
s=[i[0]+i[1]for i in ab]
print(sum(s[::2])-sum(b))

Submission status: Accepted

Solution code:
from collections import deque
N=int(input())

C=[]
D=0
for _ in range(N):
    a,b=map(int,input().split())
    C.append((a,b))
    D+=b
    
C.sort(key=lambda x:x[0]+x[1])
C=deque(C)

i=0
A=0
while C:
    (a,b)=C.pop()
    if i==0:
        A+=a+b
    i^=1
print(A-D)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

N = int(readline())
A = [0] * N
B = [0] * N
C = [0] * N
for i in range(N):
  A[i],B[i] = map(int,readline().split())
  C[i] = (A[i] + B[i], i)
  
C = sorted(C, key = lambda x:x[0], reverse = True)

ans = 0
for i in range(len(C)):
  if i % 2 == 0:
    ans += A[C[i][1]]
  else:
    ans -= B[C[i][1]]
    
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
ab=[]
for i in range(n):
    a,b=map(int,input().split())
    ab.append([a+b,a,b])
ab.sort(reverse=True)
#print(ab)

taka=0
aoki=0

for i in range(1,n+1):
    if i%2!=0:
        taka+=ab[i-1][1]
    else:
        aoki+=ab[i-1][2]
ans=taka-aoki
print(ans)

Submission status: Accepted

Solution code:
N, *AB = map(int, open(0).read().split())
AB = [(a, b) for a, b in zip(*[iter(AB)] * 2)]
AB.sort(key=lambda x: x[0] + x[1], reverse=True)
ans = sum(a for a, _ in AB)
for a, b in AB[1::2]:
    ans -= a + b
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
l = [list(map(int,input().split())) for i in range(n)]
ab = []
ans = 0
for i,j in l:
    ab.append(i+j)
    ans -= j

ab.sort(reverse=True)
ans += sum(ab[::2])
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
food = [[int(i) for i in input().split()] for _ in range(n)]
food.sort(key=lambda x:sum(x),reverse=True)
hpns = [0,0]
for i in range(n): hpns[i%2] += food[i][i%2]
print(hpns[0]-hpns[1])

Submission status: Accepted

Solution code:
import numpy as np
n = int(input())
al = np.zeros(n)
bl = np.zeros(n)
for i in range (n):
    al[i],bl[i] = map(int,input().split())
id = [*range(n)]
s=al+bl
id = sorted(id, key=lambda i: -s[i])
s=np.sort(s)
ans = 0 
for i in range(n):
    if i%2==0:
        ans+=al[id[i]]
    else:
        ans-=bl[id[i]]
print(int(ans))

Submission status: Accepted

Solution code:
from sys import stdin, setrecursionlimit


def main():
    input = stdin.buffer.readline
    n = int(input())
    ab = [list(map(int, input().split())) for _ in range(n)]
    for i in range(n):
        ab[i].append(ab[i][0] + ab[i][1])
    arr = sorted(ab, reverse=True, key=lambda x: x[2])
    ans = 0
    for i in range(n):
        if i % 2 == 0:
            ans += arr[i][0]
        else:
            ans -= arr[i][1]
    print(ans)


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

Submission status: Accepted

Solution code:
n=int(input())
ab=[list(map(int, input().split())) for _ in range(n)]
yusendo=[]
for i in range(n):
    yusendo.append([ab[i][0]+ab[i][1], ab[i][1]-ab[i][0], i])
yusendo.sort(reverse=True)
# print(yusendo)

takahashi=0
aoki=0
for i in range(n):
    if i%2==0:
        takahashi+=ab[yusendo[i][2]][0]
    else:
        aoki+=ab[yusendo[i][2]][1]
# print(takahashi, aoki)

print(takahashi-aoki)

Submission status: Accepted

Solution code:
n = int(input())
score = []
for i in range(n):
  a,b = map(int,input().split())
  score.append([a,b])
sorted_score = sorted(score, key=lambda x: x[0]+x[1], reverse=True)
i=0
t_score = 0
a_score = 0
for i,scores in enumerate(sorted_score):
  if i%2==0:
    t_score+=scores[0]
  else:
    a_score+=scores[1]
print(t_score-a_score)

Submission status: Accepted

Solution code:
n = int(input())
ab = []
for _ in range(n):
    a, b = map(int, input().split())
    ab.append([a + b, a, b])
ab.sort(reverse = True)

num = (n + 1) // 2
ans = 0
for i in range(n):
    if i % 2 == 0:
        ans += ab[i][1]
    else:
        ans -= ab[i][2]
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
L = []
for _ in range(n):
    a,b = map(int,input().split())
    L.append(((a+b),a,b))
L.sort(reverse=True)
ta = 0
ao = 0
for i in range(n):
    if i % 2 == 0:
        ta += L[i][1]
    else:
        ao += L[i][2]
print(ta-ao)

Submission status: Accepted

Solution code:
N = int(input())
l = []
for i in range(N):
    a,b = map(int,input().split())
    l.append((a+b,a,b))
l.sort(reverse=True)
A,B = 0,0
for i in range(N):
    if i%2 == 0:
        A += l[i][1]
    else:
        B += l[i][2]
print(A-B)

Submission status: Accepted

Solution code:
n = int(input())

a, b, ab = [], [], []
for _ in range(n):
    ai, bi = map(int, input().split())
    a.append(ai)
    b.append(bi)
    ab.append(ai + bi)
ab.sort(reverse=True)

ans = -sum(b)
for i in range(0, n, 2):
    ans += ab[i]
print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = [0] * N
    B = [0] * N
    C = [0] * N
    for i in range(N):
        A[i], B[i] = map(int, input().split())
        C[i] = A[i] + B[i]

    C.sort(reverse=True)
    ans = -sum(B)
    for i, c in enumerate(C):
        if i % 2 == 0:
            ans += C[i]
    
    print(ans) 

    
    



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

def main():
    N = int(input())
    S = [None]*N
    for _ in range(N):
        a,b = map(int,input().split())
        S[_] = [a+b, a, b]
    S.sort(reverse = True)
    ret = 0
    for i in range(N):
        if i%2==0:
            ret += S[i][1]
        else:
            ret -= S[i][2]
#        print(i,ret)
    print(ret)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
AB=[]
for _ in range(N):
    a,b=map(int,input().split())
    AB.append([a+b,a,b])
AB.sort(reverse=True)

ans=0
for i in range(N):
    if i%2==0:
        ans+=AB[i][1]
    else:
        ans-=AB[i][2]
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
datA = []
datB = []
buf = []
for i in range(n):
    a,b = map(int, input().split())
    datA.append(a)
    datB.append(b)
    buf.append([a+b,i])
buf.sort(reverse=True)
resA, resB = 0, 0
for i in range(n):
    if i%2 == 0:
        resA += datA[buf[i][1]]
    else:
        resB += datB[buf[i][1]]

print(resA - resB)

Submission status: Accepted

Solution code:
n = int(input())

dishes = []
for _ in range(n):
    a, b = map(int, input().split())
    dishes.append((a+b, a, b))
dishes.sort(reverse=True)

T = A = 0
for i, (_, a, b) in enumerate(dishes):
    if not i & 1:
        T += a
    else:
        A += b
print(T-A)

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AtoZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  divisors.sort()
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N = I()
D = []
for _ in range(N):
  a,b = IL()
  D.append((a,b))
D = sorted(D,key = lambda x:sum(x),reverse = True)

A = 0
B = 0
for i in range(N):
  a,b = D[i]
  if i%2:
    B+=b
  else:
    A+=a

print(A-B)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
a = [None]*n
b = [None]*n
for i in range(n):
    a[i],b[i] = map(int, input().split())
    
ab = [(a[i]+b[i], i) for i in range(n)]
ab.sort(reverse=True)
takahashi = 0
aoki = 0
for i in range(n):
    if i%2==0:
        takahashi += a[ab[i][1]]
    else:
        aoki += b[ab[i][1]]
print(takahashi-aoki)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
a = [None]*n
b = [None]*n
for i in range(n):
    a[i],b[i] = map(int, input().split())
    
ab = [(a[i]+b[i], i) for i in range(n)]
ab.sort()
takahashi = 0
aoki = 0
for i in range(n):
    if i%2==0:
        takahashi += a[ab[n-1-i][1]]
    else:
        aoki += b[ab[n-1-i][1]]
print(takahashi-aoki)

Submission status: Accepted

Solution code:
import numpy as np
n = int(input())

aab = []

for i in range(n):
    a, b = map(int, input().split())
    aab.append([a + b, a, b])

aab.sort(reverse=True)
aab = np.array(aab)

a = aab[:, 1][0::2].sum()
b = aab[:, 2][1::2].sum()

print(a - b)

Submission status: Accepted

Solution code:
n = int(input())
L = []
ans = 0
for _ in range(n):
    a, b = map(int, input().split())
    L.append([a, b, a + b])
L.sort(key=lambda x: x[2], reverse=True)
for i in range(0, n, 2):
    ans += L[i][0]
for i in range(1, n, 2):
    ans -= L[i][1]
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
l = []
for _ in range(N):
    A, B = map(int, input().split())
    l.append((-abs(A+B), -A, -B))
l.sort()
a, b = 0, 0
for i in range(N):
    if i%2:
        b -= l[i][2]
    else:
        a -= l[i][1]

print(a-b)

Submission status: Accepted

Solution code:
N = int(input())
AB = [list(map(int,input().split())) for _ in range(N)]

l = []
T,A = 0,0

for a,b in AB:
  l.append(a+b)
  T += a
  A += b

ans = -A
l.sort(reverse = True)

check = 0

for i in range(N):
  if check == 0:
    ans += l[i]
    check = 1
  else:
    check = 0
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
data = []
for i in range(n):
    a, b = map(int, input().split())
    data.append([a, b, a+b])
a_ans = 0
b_ans = 0
data.sort(key=lambda x: x[2] ,reverse=True)
for i in range(n):
    if i % 2 == 0:
        a_ans += data[i][0]
    else:
        b_ans += data[i][1]
print(a_ans - b_ans)

Submission status: Accepted

Solution code:
n = int(input())
A, B, AB = [], [], []
for i in range(n):
    ai, bi = map(int, input().split())
    A.append(ai)
    B.append(bi)
    AB.append((ai + bi, i))
AB.sort(reverse=True)


ans = 0
for i in range(n):
    if i % 2 == 0:
        ans += A[AB[i][1]]
    else:
        ans -= B[AB[i][1]]
print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    N = int(input())
    C = [0] * N
    for n in range(N):
        a, b = [int(x) for x in input().strip().split()]
        C[n] = (a+b, a, b)
    C.sort(reverse=True)
    ans = 0
    for n in range(N):
        if n % 2:
            ans -= C[n][2]
        else:
            ans += C[n][1]

    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
s=[]
for i in range(n):
  a,b=map(int,input().split())
  s.append([a+b,a,b])
s=sorted(s,key=lambda x: x[0],reverse=True)
tk,ao=0,0
for i in range(n):
  if i%2==0:
    tk+=s[i][1]
  else:
    ao+=s[i][2]
print(tk-ao)

Submission status: Accepted

Solution code:
def f():
    import sys
    input=sys.stdin.buffer.readline
    sys.setrecursionlimit(10**9)
    n=int(input())
    l=sorted([list(map(int,input().split())) for i in range(n)],key=sum,reverse=1)
    ans=0
    for i in range(n):
        if i%2:ans-=l[i][1]
        else:ans+=l[i][0]
    print(ans)
if __name__ == "__main__":
    f()

Submission status: Accepted

Solution code:
import sys
import heapq
import math
import fractions
import bisect
import itertools
from collections import Counter
from collections import deque
from operator import itemgetter
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

n=int(input())
a=[0]*n
b=[0]*n
l=[0]*n
for i in range(n):
    x,y=mp()
    a[i]=x
    b[i]=y
    l[i]=[x,y,x+y]
l=sorted(l,key=lambda X: X[2],reverse=True)
ans=0
for i in range(n):
    if i%2==0:
        ans+=l[i][0]
    else:
        ans-=l[i][1]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())

AB=[list(map(int,input().split())) for i in range(n)]

AB.sort(key=lambda x:x[0]+x[1],reverse=True)

if len(AB)%2==1:
    AB.append([0,0])

s=0
for i in range(0,len(AB),2):
    s+=AB[i][0]-AB[i+1][1]

print(s)