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: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
ab = []

for _ in range(n):
    ab.append(tuple(map(int, input().split())))

flag = True
a = 0
b = 0
for _ in range(n):
    if flag:
        ab = sorted(ab, key=lambda x: (x[0], x[1]))
        a += ab.pop()[0]
    else:
        ab = sorted(ab, key=lambda x: (x[1], x[0]))
        b += ab.pop()[1]
    flag = not(flag)

print(a - b)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

aa = []
for i in range(n):
	k,l = map(int,input().split())
	aa.append([k,l])
dp = [[0,0] for i in range(n+1)]
aa.sort(key = lambda x:x[1])
co = 0
ma = 0
kkk = 0
for i in range(n):
	if i % 2 == 0:
		for j in range(len(aa)):
			if ma < aa[j][0]:
				ma = aa[j][0]
				kkk = j
		co += aa.pop(j)[0]
	else:
		for j in range(len(aa)):
			if ma < aa[j][1]:
				ma = aa[j][1]
				kkk = j
		co -= aa.pop(j)[1]

print(co)

Submission status: Time Limit Exceeded

Solution code:
import sys
from operator import itemgetter
input = sys.stdin.readline

N = int(input())
A, B = [], []

for i in range(N):
    a, b = map(int, input().split())
    A.append([a, i])
    B.append([b, i])
A.sort(reverse=True, key=itemgetter(1))
B.sort(reverse=True, key=itemgetter(1))

ate = []
apoint, apos = 0, 0
bpoint, bpos = 0, 0
for i in range(N):
    if i % 2 == 0:
        while A[apos][1] in ate:
            apos += 1
        apoint += A[apos][0]
        ate.append(A[apos][1])
        apos += 1
    else:
        while B[bpos][1] in ate:
            bpos += 1
        bpoint += B[bpos][0]
        ate.append(B[bpos][1])
        bpos += 1
print(apoint - bpoint)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())

A_list = []
B_list = []
takahashi_list = []
aoki_list = []
for i in range(N):
    A, B = map(int, input().split())
    A_list.append(A)
    B_list.append(B)
    takahashi_list.append(B - A)
    aoki_list.append(B - A)

A_list = np.array(A_list)
B_list = np.array(B_list)
takahashi_list = np.array(takahashi_list)
aoki_list = np.array(aoki_list)

takahashi_score = 0
aoki_score = 0
for i in range(N):
    if len(takahashi_list) != 0:
        dish_index = takahashi_list.argmax()
        score = A_list[dish_index]
        takahashi_score += score

        A_list = np.delete(A_list, dish_index, 0)
        B_list = np.delete(B_list, dish_index, 0)
        takahashi_list = np.delete(takahashi_list, dish_index, 0)
        aoki_list = np.delete(aoki_list, dish_index, 0)

    if len(aoki_list) != 0:
        dish_index = aoki_list.argmax()
        score = B_list[dish_index]
        aoki_score += score

        A_list = np.delete(A_list, dish_index, 0)
        B_list = np.delete(B_list, dish_index, 0)
        takahashi_list = np.delete(takahashi_list, dish_index, 0)
        aoki_list = np.delete(aoki_list, dish_index, 0)

print(takahashi_score - aoki_score)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = []
b = []
sum = []
ans = 0
for i in range(n):
  l, m = map(int, input().split())
  a.append(l)
  b.append(m)
  sum.append(l+m)
for i in range(n):
  _index = sum.index(max(sum))
  if i % 2 == 0:
    ans += a[_index]
  else:
    ans -= b[_index]
  sum.pop(_index)
  a.pop(_index)
  b.pop(_index)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n = int(input())
a = []
b = []
aa = []
bb = []
for i in range(n):
  ai,bi = list(map(int, input().split()))
  a.append(ai)
  b.append(bi)
  if ai == bi:
    aa.append(ai+bi)
    bb.append(ai+bi)
  elif ai > bi:
    aa.append(bi)
    bb.append(ai+bi)
  else:
    aa.append(bi+ai)
    bb.append(ai)
alice = 0
bob = 0
aa = np.array(aa)
bb = np.array(bb)
for i in range(n):
  if i % 2 == 0:
    w = np.argmax(aa)
    alice += a[w]
    aa[w] = 0
    bb[w] = 0
  else:
    w = np.argmax(bb)
    bob += b[w]
    aa[w] = 0
    bb[w] = 0
print(alice-bob)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
D = [list(map(int,input().split()))+[k] for k in range(N)]

T = sorted(D, key = lambda x: (-x[0],-x[1]))
A = sorted(D, key = lambda x: (-x[1],-x[0]))
U = [1 for k in range(N)]

ans = 0
l = 0
m = 0
for k in range(N):
    if k%2 == 0:
        while U[T[l][2]] == 0:
            l += 1
        ans += T[l][0]
        U[T[l][2]] = 0
    else:
        m = 0
        while U[A[m][2]] == 0:
            m += 1
        ans -= A[m][1]
        U[A[m][2]] = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
Alist = []
Blist = []
sumlist = []

for i in range(N):
    a,b = map(int,input().split())
    Alist.append(a)
    Blist.append(b)
    sumlist.append(a+b)

counter = 0
takahasi = 0
aoki = 0
for i in range(N):
    if counter == 0:
        takahasi += Alist[sumlist.index(max(sumlist))]
        sumlist[sumlist.index(max(sumlist))] = 0
        counter = 1
        continue
    if counter == 1:
        aoki += Blist[sumlist.index(max(sumlist))]
        sumlist[sumlist.index(max(sumlist))] = 0
        counter = 0
        continue

print(takahasi-aoki)

Submission status: Time Limit Exceeded

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

dif = [data[i][0] - data[i][1] for i in range(N)]
A = [data[i][0] for i in range(N)]
B = [data[i][1] for i in range(N)]
count1 = 0
count2 = 0

def fa():
    if max(dif) > 0 or min(dif) < 0:
        if max(dif) > -min(dif):
            index = dif.index(max(dif))
        else:
            index = dif.index(min(dif))
    else:
        index = A.index(max(A))

    dif.pop(index)
    B.pop(index)
    return A.pop(index)

def fb():
    if max(dif) > 0 or min(dif) < 0:
        if max(dif) < -min(dif):
            index = dif.index(max(dif))
        else:
            index = dif.index(min(dif))
    else:
        index = A.index(max(A))

    dif.pop(index)
    A.pop(index)
    return B.pop(index)

while True:
    count1 += fa()
    if len(A) == 0:
        break
    count2 += fb()
    if len(A) == 0:
        break

print(count1 - count2)

Submission status: Time Limit Exceeded

Solution code:

import numpy as np


def _main():
    N = int(input())
    A, B = [], []
    for _ in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
    AB = np.array([A, B], dtype=np.int64)
    AB_sorted = AB.argsort(axis=-1)

    scores = [0, 0]  # 高橋くん, 青木さん
    mask = np.ones((N,), dtype=bool)
    turn = 0
    for _ in range(N):
        max1 = AB_sorted[turn, mask][-1]
        max2 = AB_sorted[turn ^ 1, mask][-1]
        if AB[turn, max1] >= AB[turn ^ 1, max2]:
            eat = max1
        else:
            eat = max2
        scores[turn] += AB[turn, eat]
        mask[eat] = False
        turn ^= 1

    print(np.int64(scores[0] - scores[1]))


if __name__ == '__main__':
    _main()

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
LA=[0]*N
LB=[0]*N
LD=[0]*N
for i in range(N):
    A,B=[int(x) for x in input().split()]
    LA[i]=A
    LB[i]=B

PA=0
PB=0
for i in range(N):
    LD[i]=(LA[i]+LB[i])
    
for i in range(int(N/2)):
    mx=LD.index(max(LD))
    LD[mx]=0
    PA+=LA[mx]
    mx=LD.index(max(LD))
    LD[mx]=0
    PB+=LB[mx]

if N%2==1:
    mx=LD.index(max(LD))
    LD[mx]=0
    PA+=LA[mx]

print(PA-PB)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=[]
B=[]
takahashi=0
aoki=0
for i in range(N):
    a,b=map(int,input().split())
    A.append(a)
    B.append(b)
for i in range(N):
    if not B or not A:
        break
    if max(A)>=max(B):
        num=A.index(max(A))
        takahashi+=A[num]
        del A[num]
        del B[num]
    else:
        num=B.index(max(B))
        takahashi+=A[num]
        del A[num]
        del B[num]
    if not B or not A:
        break
    if max(B)>=max(A):
        num=B.index(max(B))
        aoki+=B[num]
        del A[num]
        del B[num]
    else:
        num=A.index(max(A))
        aoki+=B[num]
        del A[num]
        del B[num]
print(takahashi-aoki)

Submission status: Time Limit Exceeded

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

A=0
B=0
for i in range(N):
  if i%2==0:
    m=max(D, key=lambda x:x[0])
    tmp=[d for d in D if d[0]==m[0]]
    t=max(tmp, key=lambda x:x[1])
    A+=t[0]
    D.remove(t)
  else:
    m=max(D, key=lambda x:x[1])
    tmp=[d for d in D if d[1]==m[1]]
    t=max(tmp, key=lambda x:x[0])
    B+=t[1]
    D.remove(t)
  
print(A-B)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
D = [list(map(int,input().split())) for k in range(N)]
for k in range(N):
    D[k].append(k)

T = sorted(D, key = lambda x: (-x[0],-x[1]))
A = sorted(D, key = lambda x: (-x[1],-x[0]))
U = [1 for k in range(N)]

ans = 0
l = 0
m = 0
for k in range(N):
    if k%2 == 0:
        while U[T[l][2]] == 0:
            l += 1
        ans += T[l][0]
        U[T[l][2]] = 0
    else:
        m = 0
        while U[A[m][2]] == 0:
            m += 1
        ans -= A[m][1]
        U[A[m][2]] = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A,B=[],[]
for i in range(N):
  a,b=map(int,input().split())
  A.append((a,b,i))
  B.append((b,a,i))
A.sort()
B.sort()
ans=0
inf=float("inf")
eaten=[False]*N
for i in range(N):
  if i%2==0:
    while eaten[A[-1][2]]:
      A.pop()
    while eaten[B[-1][2]]:
      B.pop()
    a1=A[-1][0]
    a2,b1=B[-1][1],B[-1][0]
    if A[-1][2]==B[-1][2]:
      ans+=a1
      eaten[A[-1][2]]=True
    else:
      b2=inf
      if i<N-1:
        while b2>10000000000:
          k=2
          if not eaten[B[-k][2]]:
            b2=B[-k][0]
          else:
            k+=1
      if a1-b1>=a2-b2:
        ans+=a1
        eaten[A[-1][2]]=True
      else:
        ans+=a2
        eaten[B[-1][2]]=True
  else:
    while eaten[A[-1][2]]:
      A.pop()
    while eaten[B[-1][2]]:
      B.pop()
    b1=B[-1][0]
    b2,a1=A[-1][1],A[-1][0]
    if A[-1][2]==B[-1][2]:
      ans-=b1
      eaten[B[-1][2]]=True
    else:
      a2=inf
      if i<N-1:
        while a2>10000000000:
          k=2
          if not eaten[A[-k][2]]:
            a2=A[-k][0]
          else:
            k+=1
      if b1-a1>=b2-a2:
        ans+=b1
        eaten[B[-1][2]]=True
      else:
        ans+=b2
        eaten[A[-1][2]]=True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
# import bisect
# import math
# import numpy as np


"""Template"""


class IP:
    """
    入力を取得するクラス
    """
    def __init__(self):
        self.input = sys.stdin.readline

    def I(self):
        """
        1文字の取得に使います
        :return: int
        """
        return int(self.input())

    def S(self):
        """
        1文字の取得(str
        :return: str
        """
        return self.input()

    def IL(self):
        """
        1行を空白で区切りリストにします(int
        :return: リスト
        """
        return list(map(int, self.input().split()))

    def SL(self):
        """
        1行の文字列を空白区切りでリストにします
        :return: リスト
        """
        return list(map(str, self.input().split()))

    def ILS(self, n):
        """
        1列丸々取得します(int
        :param n: 行数
        :return: リスト
        """
        return [int(self.input()) for _ in range(n)]

    def SLS(self, n):
        """
        1列丸々取得します（str
        :param n: 行数
        :return: リスト
        """
        return [self.input() for _ in range(n)]

    def SILS(self, n):
        """
        Some Int LineS
        横に複数、縦にも複数
        :param n: 行数
        :return: list
        """
        return [self.IL() for _ in range(n)]


class Idea:
    def __init__(self):
        pass

    def HF(self, p):
        """
        Half enumeration
        半分全列挙です
        pの要素の和の組み合わせを作ります。
        ソート、重複削除行います
        :param p: list : 元となるリスト
        :return: list : 組み合わせられた和のリスト
        """
        return sorted(set(p[i] + p[j] for i in range(len(p)) for j in range(i, len(p))))

    def Bfs2(self, a):
        """
        bit_full_search2
        bit全探索の改良版
        全探索させたら2進数のリストと10進数のリストを返す
        :return: list２つ : １個目 2進数(16桁)  2個目 10進数
        """
        # 参考
        # https://blog.rossywhite.com/2018/08/06/bit-search/
        # https://atcoder.jp/contests/abc105/submissions/4088632
        value = []
        for i in range(1 << len(a)):
            output = []

            for j in range(len(a)):
                if self.bit_o(i, j):
                    """右からj+1番目のiが1かどうか判定"""
                    # output.append(a[j])
                    output.append(a[j])
            value.append([format(i, 'b').zfill(16), sum(output)])

        value.sort(key=lambda x: x[1])
        bin = [value[k][0] for k in range(len(value))]
        val = [value[k][1] for k in range(len(value))]
        return bin, val

    def SR(self, s):
        """
        昇順ソート（reverse書くのが面倒
        返り値はありません。注意して下さい。
        SR(s) と書いたらsが昇順ソートされるだけです。
        Sort Reverse
        :param s: ソートしたいリスト
        :return: None
        """
        s.sort(reverse=True)

    def bit_n(self, a, b):
        """
        bit探索で使います。0以上のときにTrue出します
        自然数だからn
        :param a: int
        :param b: int
        :return: bool
        """
        return bool((a >> b & 1) > 0)

    def bit_o(self, a, b):
        """
        bit探索で使います。1のときにTrue出すよ
        oneで1
        :param a: int
        :param b: int
        :return: bool
        """
        return bool(((a >> b) & 1) == 1)

    def ceil(self, x, y):
        """
        Round up
        小数点切り上げ割り算
        :param x: int
        :param y: int
        :return: int
        """
        return -(-x//y)

    def ave(self, a):
        """
        平均を求めます
        :param a: list
        :return: int
        """
        return sum(a) / len(a)


"""ここからメインコード"""


def main():
    # 1文字に省略
    r, e = range, enumerate
    ip = IP()
    id = Idea()

    """この下から書いてね"""
    n = ip.I()
    s = ip.SILS(n)
    a = b = 0

    for i in r(n):
        if i % 2 == 0:
            s.sort()
            a += s[-1][0]
            s.pop(-1)
        else:
            s.sort(key=lambda x: x[1])
            b += s[-1][1]
            s.pop(-1)

    print(a - b)


main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

S = []

for i in range(N):
    a, b = map(int, input().split())
    tmp = [a, b]
    S.append(tmp)
    
ta = 0
ao = 0
    
for i in range(N):
    if i%2==0:
        S.sort(key=lambda x:x[0])
        S.reverse()
        
        f = 1
        num = 0
        al = S[0]
        now = 0
        
        while num<len(S)-1 and f>0:
            if S[num][0]!=S[num+1][0]:
                f = -1
            else:
                if S[num+1][1]>al[1]:
                    al = S[num+1]
                    now = num+1
                num = num+1
           
        ta = ta+S[now][0]
        del S[now]
    else:
        S.sort(key=lambda x:x[1])
        S.reverse()
        
        f = 1
        num = 0
        al = S[0]
        now = 0
        
        while num<len(S)-1 and f>0:
            if S[num][1]!=S[num+1][1]:
                f = -1
            else:
                if S[num+1][0]>al[0]:
                    al = S[num+1]
                    now = num+1
                num = num+1
           
        ao = ao+S[now][1]
        del S[now]

print(ta-ao)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = []
b = []
aa = []
bb = []
for i in range(n):
  ai,bi = list(map(int, input().split()))
  a.append(ai)
  b.append(bi)
  if ai == bi:
    aa.append(ai+bi)
    bb.append(ai+bi)
  elif ai > bi:
    aa.append(0)
    bb.append(ai+bi)
  else:
    aa.append(bi+ai)
    bb.append(0)
alice = 0
bob = 0
for i in range(n):
  if i % 2 == 0:
    w = aa.index(max(aa))
    alice += a[w]
    aa[w] = 0
    bb[w] = 0
  else:
    w = bb.index(max(bb))
    bob += b[w]
    aa[w] = 0
    bb[w] = 0
print(alice-bob)

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter

N = int(input())
A, B = [], []

for i in range(N):
    a, b = map(int, input().split())
    A.append([a, i])
    B.append([b, i])
A.sort(reverse=True, key=itemgetter(1))
B.sort(reverse=True, key=itemgetter(1))

ate = []
apoint, apos = 0, 0
bpoint, bpos = 0, 0
for i in range(N):
    if i % 2 == 0:
        while True:
            if A[apos][1] not in ate:
                apoint += A[apos][0]
                ate.append(A[apos][1])
                break
            apos += 1
    else:
        while True:
            if B[bpos][1] not in ate:
                bpoint += B[bpos][0]
                ate.append(B[bpos][1])
                break
            bpos += 1
print(apoint - bpoint)

Submission status: Time Limit Exceeded

Solution code:

import numpy as np


def _main():
    N = int(input())
    A, B = [], []
    for _ in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
    AB = np.array([A, B], dtype=np.int64)

    scores = [0, 0]  # 高橋くん, 青木さん
    mask = np.ones((N,), dtype=bool)
    turn = 0
    for _ in range(N):
        max1 = AB[turn, mask].argmax()
        max2 = AB[turn ^ 1, mask].argmax()
        if AB[turn, max1] >= AB[turn ^ 1, max2]:
            eat = max1
        else:
            eat = max2
        scores[turn] += AB[turn, eat]
        mask[eat] = False
        turn ^= 1

    print(np.int64(scores[0] - scores[1]))


if __name__ == '__main__':
    _main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = []
b = []
aa = []
bb = []
for i in range(n):
  ai,bi = list(map(int, input().split()))
  a.append(ai)
  b.append(bi)
  if ai == bi:
    aa.append(ai+bi)
    bb.append(ai+bi)
  elif ai > bi:
    aa.append(0)
    bb.append(ai+bi)
  else:
    aa.append(bi+ai)
    bb.append(0)
alice = 0
bob = 0
for i in range(n):
  if i % 2 == 0:
    w = aa.index(max(aa))
    alice += a[w]
    a.pop(w)
    b.pop(w)
    aa.pop(w)
    bb.pop(w)
  else:
    w = bb.index(max(bb))
    bob += b[w]
    a.pop(w)
    b.pop(w)
    aa.pop(w)
    bb.pop(w)
print(alice-bob)

Submission status: Time Limit Exceeded

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

A=0
B=0
for i in range(N):
  if i%2==0:
    D.sort(reverse=True, key=lambda x:x[0])
    tmp=[d for d in D if d[0]==D[0][0]]
    tmp.sort(reverse=True, key=lambda x:x[1])
    A+=tmp[0][0]
    D.remove(tmp[0])
  else:
    D.sort(reverse=True, key=lambda x:x[1])
    tmp=[d for d in D if d[1]==D[0][1]]
    tmp.sort(reverse=True, key=lambda x:x[0])
    B+=tmp[0][1]
    D.remove(tmp[0])
  
print(A-B)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
takahashi_u = []
aoki_u = []
sum_u = []
takahashi_eat = []
aoki_eat = []
for i in range(n):
  a, b = map(int, input().split())
  takahashi_u.append(a)
  aoki_u.append(b)
  sum_u.append(a+b)
for i in range(n):
  turn = i % 2
  # takahashi
  m_index = sum_u.index(max(sum_u))
  sum_u.pop(m_index)
  if turn == 0:
    takahashi_eat.append(takahashi_u.pop(m_index))
    aoki_u.pop(m_index)
  # aoki
  else:
    aoki_eat.append(aoki_u.pop(m_index))
    takahashi_u.pop(m_index)
print(sum(takahashi_eat) - sum(aoki_eat))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a, b = [], []
for _ in range(n):
    x, y = map(int, input().split())
    a.append(x)
    b.append(y)


who = True
dishes = list(range(n))
takahashi = aoki = 0
while dishes:
    if who:
        dishes.sort(key=lambda dish: (b[dish], a[dish]))
        takahashi += a[dishes.pop()]
    else:
        dishes.sort(key=lambda dish: (a[dish], b[dish]))
        aoki += b[dishes.pop()]
    who = not who

print(takahashi - aoki)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
f=[0]*n
d=[list(map(int,input().split()))+[i]for i in range(n)]
t=sorted(d,key=lambda x:(x[0]-x[1],-x[0]))
a=sorted(d,key=lambda x:(x[0]-x[1],-x[1]))
sumt=suma=0
while t:
    x=t.pop(0)
    while t and f[x[2]]:
        x=t.pop(0)
    if not f[x[2]]:
        sumt+=x[0]
    f[x[2]]=1
    if a:
        y=a.pop(0)
        while a and f[y[2]]:
            y=a.pop(0)
        if not f[y[2]]:
            suma+=y[1]
        f[y[2]]=1
print(sumt-suma)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=[]
B=[]
for i in range(N):
	x,y=list(map(int,input().split()))
	A.append(x)
	B.append(y)

C=[]
for i in range(N):
	C.append(A[i]+B[i])

get=0
lose=0
while True:
	get+=A[C.index(max(C))]
	C[C.index(max(C))]=0
	if max(C)==0: break
	lose+=B[C.index(max(C))]
	C[C.index(max(C))]=0
	if max(C)==0: break

print(get-lose)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
import math
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()
def IIR(n): return [II() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
mod = 1000000007

#A
"""
n,a,b = LI()
ans = [min(a,b),max(0,a+b-n)]
print(ans[0],ans[1])
"""

#B
"""
n = II()
a = S()
b = S()
c = S()
ans = 0
for i in range(n):
    if a[i] == b[i]:
        if b[i] == c[i]:
            continue
        else:
            ans += 1
    else:
        if b[i] == c[i] or c[i] == a[i]:
            ans += 1
        else:
            ans += 2
print(ans)
"""

#C
n = II()
c = LIR(n)
a = []
lis = [True for i in range(n)]
for i in range(n):
    a.append(c[i]+[i])
a.sort(key = lambda x:-x[0]-x[1])
count = 0
ans = 0
i = 0
while count < n:
    x,y,z = a.pop(0)
    if lis[z]:
        count += 1
        i ^= 1
        lis[z] = False
        if i == 1:
            ans += x
        else:
            ans -= y
print(ans)
#D

#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

L = list(list(map(int,input().split())) for i in range(N))
#print(L)
turn = "taka"
takapoint = 0
aokipoint = 0

while len(L) :
    if turn == "taka" :
        L = sorted(L,key=lambda x: x[1],reverse=True)
        L = sorted(L,key=lambda x: x[0],reverse=True)
        takapoint += L[0][0]
        L.pop(0)
        turn = "aoki"
    else :
        L = sorted(L,key=lambda x: x[0],reverse=True)
        L = sorted(L,key=lambda x: x[1],reverse=True)
        aokipoint += L[0][1]
        L.pop(0)
        turn = "taka"
ans = takapoint - aokipoint

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[15]:


N = int(input())
apb = []
b_sum = 0
for i in range(N):
    A,B = map(int, input().split())
    apb += [A+B]
    b_sum += B


# In[20]:


ans = sum(sorted(apb, reverse=True)[::2])-b_sum
print(ans)


# In[ ]:

Submission status: Accepted

Solution code:
n = int(input())

dish = []
ans = 0
for i in range(n):
    a, b = map(int,input().split())
    ans -= b
    dish.append(a+b)
dish.sort(reverse=True)    

for i in range(n):
    if not i%2:
        ans += dish[i]
        
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A, B, C = [], [], []
    for _ in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
        C.append(a+b)
    C.sort(reverse=True)
    ans = 0
    for i in range(N//2+N%2):
        ans += C[2*i]
    ans -= sum(B)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
d = {}
i = 0
x, s = [], []
for _ in range(n):
    a, b = map(int, input().split())
    k = a + b
    if not k in d:
        d[k] = i
        x.append([])
        s.append(k)
        i += 1
    x[d[k]].append([a, b])
t, a = 0, 0
s.sort(reverse = True)
l = len(x)
for i in range(l):
    x[i].sort(reverse = True)
now = 1
ans = 0
for i in s:
    y = x[d[i]]
    i, j = 0, len(y) - 1
    while i <= j:
        if now:
            ans += y[i][0]
            i += 1
        else:
            ans -= y[j][1]
            j -= 1
        now ^= 1
print(ans)

Submission status: Accepted

Solution code:
import math
n = int(input())

c = []
aok = 0
for i in range(n):
  a,b=map(int, input().split())
  cc  = a+b
  c.append(cc)
  aok += b
c.sort(reverse=True)

ans = sum(c[::2])-aok
print (ans)

Submission status: Accepted

Solution code:
n = int(input())
A = []
ans = 0
for _ in range(n):
  a, b = map(int, input().split())
  ans -= b
  A.append(a+b)
A.sort(reverse=True)
ans += sum(A[::2])
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
AB = [list(map(int, input().split())) for _ in range(N)]
AB = sorted(AB, key=lambda x:sum(x), reverse=True)

print(sum(map(lambda x: x[0], AB[::2])) - sum(map(lambda x: x[1], AB[1::2])))

Submission status: Accepted

Solution code:
import sys
import collections

from operator import itemgetter

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N = int(input())
    AB = [[int(x) for x in input().split()] for _ in range(N)]

    C = []

    for i, (a, b) in enumerate(AB):
        C.append((a + b, i))

    C.sort(reverse=True)

    takahashi = 0
    aoki = 0
    for i in range(N):
        j = C[i][1]
        if i % 2 == 0:
            takahashi += AB[j][0]
        else:
            aoki += AB[j][1]

    print(takahashi - aoki)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

def resolve():
    N = int(input())

    P = []
    A = []
    B = []
    for i in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
        P.append((a + b, i))

    P.sort(reverse=True)
    taka = 0
    aoki = 0
    for i, (diff, idx) in enumerate(P):
        if i % 2 == 0:
            taka += A[idx]
        else:
            aoki += B[idx]

    print(taka - aoki)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
N = int(input())
Dishes = [list(map(int,input().split())) for _ in range(N)]
Dishes.sort(key=lambda x: x[0]+x[1])
Dishes.reverse()
score = 0
for i in range(N):
    score -= Dishes[i][1]
    if(i%2==0):
        score += Dishes[i][0] + Dishes[i][1]
print(score)

Submission status: Accepted

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

l=sorted([(a+b,a,b) for a,b in ab],reverse=True)

ans=sum([a for s,a,b in l[::2]])-sum([b for s,a,b in l[1::2]])

print(ans)

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

######################################################

N=intput()
C=[]
ans=0
for _ in range(N):
    C.append(lint())
C.sort(reverse=True,key=sum)
for i in range(N):
    ans+=((-1)**(i%2))*C[i][i%2]
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
ab=[[]for _ in range(N)]
for i in range(N):
    a,b=map(int,input().split())
    ab[i]=[a+b,a,b]

ab.sort()
ab=ab[::-1]

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