Problem:


Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N  \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

7 4
1 1
2 1
3 1
4 6
4 5
4 5
4 5

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

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



Sample input:
5 3
1 9
1 7
2 6
2 5
3 1


Sample output:
26

Submission status: Runtime Error

Solution code:
#  import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import sys
#  import numpy as np
#  from queue import PriorityQueue

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    type_count = [0] * 10000
    base_point = 0
    type_bonus = 0
    #  for idx, i in enumerate(TD[:K]):
    #      #  if not type_count_dict.get(i[0]):
    #      #      type_count_dict[i[0]] = 0
    #      #  if idx < K:
    #      #  if type_count_dict[i[0]] == 0:
    #      if type_count[i[0]] == 0:
    #          type_bonus += 1
    #      #  type_count_dict[i[0]] += 1
    #      type_count[i[0]] += 1
    #      base_point += i[1]
    #  #  print(type_count_dict)

    remaining_items = []
    for idx, i in enumerate(TD):
        if idx < K:
            if type_count[i[0]] == 0:
                type_bonus += 1
            type_count[i[0]] += 1
            base_point += i[1]
        else:
            if type_count[i[0]] == 0:
                remaining_items.append(i[1])
                type_count[i[0]] += 1

    S = TD[:K]
    #  print('S', S)
    #  for i in S:
    #      type_count_dict[i[0]] += 1
    #      base_point += i[1]

    #  print('type_count', type_count_dict)
    #  base_point = sum(i[1] for i in S)
    #  type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    #  print('result', result, base_point, type_bonus)
    #  results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    #  remaining_items = []
    #  #  remaining_items = PriorityQueue()
    #  done_types = []
    #  #  print('type_count_dict', type_count_dict)
    #  for i in TD[K:]:
    #      if i[0] in done_types:
    #          continue
    #      #  if type_count_dict[i[0]] == 0:
    #      if type_count[i[0]] == 0:
    #          remaining_items.append(i[1])
    #          #  remaining_items.put((-i[1], i[1]))
    #          done_types.append(i[0])
    #  #  print('remaining_items', remaining_items)

    if len(remaining_items) == 0:
        print(result)
        return
    ridx = 0
    for s in S[::-1]:
        if len(remaining_items) < ridx + 1:
            break
        #  if remaining_items.empty():
        #      break
        #  if type_count_dict[s[0]] >= 2:
        if type_count[s[0]] >= 2:
            # print('s', s)
            #  type_count_dict[s[0]] -= 1
            type_count[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            #  base_point += remaining_items.get()[1] - s[1]
            type_bonus += 1
            ridx += 1
            #  results.append(type_bonus**2 + base_point)
            result = max(type_bonus**2 + base_point, result)

    #  print(max(results))
    print(result)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#  import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import sys
#  import numpy as np
#  from queue import PriorityQueue

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    type_count = [0] * 10000
    base_point = 0
    type_bonus = 0
    #  for idx, i in enumerate(TD[:K]):
    #      #  if not type_count_dict.get(i[0]):
    #      #      type_count_dict[i[0]] = 0
    #      #  if idx < K:
    #      #  if type_count_dict[i[0]] == 0:
    #      if type_count[i[0]] == 0:
    #          type_bonus += 1
    #      #  type_count_dict[i[0]] += 1
    #      type_count[i[0]] += 1
    #      base_point += i[1]
    #  #  print(type_count_dict)

    remaining_items = []
    for idx, i in enumerate(TD):
        if idx < K:
            if type_count[i[0]] == 0:
                type_bonus += 1
            type_count[i[0]] += 1
            base_point += i[1]
        else:
            if type_count[i[0]] == 0:
                remaining_items.append(i[1])
                type_count[i[0]] += 1

    S = TD[:K]
    #  print('S', S)
    #  for i in S:
    #      type_count_dict[i[0]] += 1
    #      base_point += i[1]

    #  print('type_count', type_count_dict)
    #  base_point = sum(i[1] for i in S)
    #  type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    #  print('result', result, base_point, type_bonus)
    #  results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    #  remaining_items = []
    #  #  remaining_items = PriorityQueue()
    #  done_types = []
    #  #  print('type_count_dict', type_count_dict)
    #  for i in TD[K:]:
    #      if i[0] in done_types:
    #          continue
    #      #  if type_count_dict[i[0]] == 0:
    #      if type_count[i[0]] == 0:
    #          remaining_items.append(i[1])
    #          #  remaining_items.put((-i[1], i[1]))
    #          done_types.append(i[0])
    #  #  print('remaining_items', remaining_items)

    if len(remaining_items) == 0:
        print(result)
        return
    ridx = 0
    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) < ridx + 1:
            break
        #  if remaining_items.empty():
        #      break
        #  if type_count_dict[s[0]] >= 2:
        if type_count[s[0]] >= 2:
            # print('s', s)
            #  type_count_dict[s[0]] -= 1
            type_count[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            #  base_point += remaining_items.get()[1] - s[1]
            type_bonus += 1
            ridx += 1
            #  results.append(type_bonus**2 + base_point)
            result = max(type_bonus**2 + base_point, result)

    #  print(max(results))
    print(result)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#  import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import sys
#  import numpy as np
#  from queue import PriorityQueue

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    type_count = [0] * 10000
    base_point = 0
    type_bonus = 0
    #  for idx, i in enumerate(TD[:K]):
    #      #  if not type_count_dict.get(i[0]):
    #      #      type_count_dict[i[0]] = 0
    #      #  if idx < K:
    #      #  if type_count_dict[i[0]] == 0:
    #      if type_count[i[0]] == 0:
    #          type_bonus += 1
    #      #  type_count_dict[i[0]] += 1
    #      type_count[i[0]] += 1
    #      base_point += i[1]
    #  #  print(type_count_dict)

    remaining_items = []
    for idx, i in enumerate(TD):
        if idx < K:
            if type_count[i[0]] == 0:
                type_bonus += 1
            type_count[i[0]] += 1
            base_point += i[1]
        else:
            if type_count[i[0]] == 0:
                remaining_items.append(i[1])
                type_count[i[0]] += 1

    S = TD[:K]
    #  print('S', S)
    #  for i in S:
    #      type_count_dict[i[0]] += 1
    #      base_point += i[1]

    #  print('type_count', type_count_dict)
    #  base_point = sum(i[1] for i in S)
    #  type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    #  print('result', result, base_point, type_bonus)
    #  results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    #  remaining_items = []
    #  #  remaining_items = PriorityQueue()
    #  done_types = []
    #  #  print('type_count_dict', type_count_dict)
    #  for i in TD[K:]:
    #      if i[0] in done_types:
    #          continue
    #      #  if type_count_dict[i[0]] == 0:
    #      if type_count[i[0]] == 0:
    #          remaining_items.append(i[1])
    #          #  remaining_items.put((-i[1], i[1]))
    #          done_types.append(i[0])
    #  #  print('remaining_items', remaining_items)

    ridx = 0
    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) < ridx + 1:
            break
        if len(remaining_items) == 0:
            break
        #  if remaining_items.empty():
        #      break
        #  if type_count_dict[s[0]] >= 2:
        if type_count[s[0]] >= 2:
            # print('s', s)
            #  type_count_dict[s[0]] -= 1
            type_count[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            #  base_point += remaining_items.get()[1] - s[1]
            type_bonus += 1
            ridx += 1
            #  results.append(type_bonus**2 + base_point)
            result = max(type_bonus**2 + base_point, result)

    #  print(max(results))
    print(result)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#  import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import sys
#  import numpy as np
#  from queue import PriorityQueue

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    type_count = [0] * 10000
    base_point = 0
    type_bonus = 0
    for idx, i in enumerate(TD):
        #  if not type_count_dict.get(i[0]):
        #      type_count_dict[i[0]] = 0
        if idx < K:
            #  if type_count_dict[i[0]] == 0:
            if type_count[i[0]] == 0:
                type_bonus += 1
            #  type_count_dict[i[0]] += 1
            type_count[i[0]] += 1
            base_point += i[1]
    #  print(type_count_dict)

    S = TD[:K]
    #  print('S', S)
    #  for i in S:
    #      type_count_dict[i[0]] += 1
    #      base_point += i[1]

    #  print('type_count', type_count_dict)
    #  base_point = sum(i[1] for i in S)
    #  type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    #  results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    remaining_items = []
    #  remaining_items = PriorityQueue()
    done_types = []
    #  print('type_count_dict', type_count_dict)
    for i in TD[K:]:
        if i[0] in done_types:
            continue
        #  if type_count_dict[i[0]] == 0:
        if type_count[i[0]] == 0:
            remaining_items.append(i[1])
            #  remaining_items.put((-i[1], i[1]))
            done_types.append(i[0])
    #  print('remaining_items', remaining_items)

    ridx = 0
    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) < ridx + 1:
            break
        if len(remaining_items) == 0:
            break
        #  if remaining_items.empty():
        #      break
        #  if type_count_dict[s[0]] >= 2:
        if type_count[s[0]] >= 2:
            # print('s', s)
            #  type_count_dict[s[0]] -= 1
            type_count[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            #  base_point += remaining_items.get()[1] - s[1]
            type_bonus += 1
            ridx += 1
            #  results.append(type_bonus**2 + base_point)
            result = max(type_bonus**2 + base_point, result)

    #  print(max(results))
    print(result)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
#  import numpy as np

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    for i in TD:
        if not type_count_dict.get(i[0]):
            type_count_dict[i[0]] = 0
    #  print(type_count_dict)

    S = TD[:K]
    #  print('S', S)
    for i in S:
        type_count_dict[i[0]] += 1

    #  print('type_count', type_count_dict)
    base_point = sum(i[1] for i in S)
    type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    remaining_items = []
    done_types = []
    #  print('type_count_dict', type_count_dict)
    for i in TD[K:]:
        if i[0] in done_types:
            continue
        if type_count_dict[i[0]] == 0:
            remaining_items.append(i[1])
            done_types.append(i[0])
    #  print('remaining_items', remaining_items)

    ridx = 0
    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) == 0:
            break
        if type_count_dict[s[0]] >= 2:
            # print('s', s)
            type_count_dict[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            type_bonus += 1
            ridx += 1
            results.append(type_bonus**2 + base_point)

    print(max(results))
   

main()

Submission status: Runtime Error

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
#  import numpy as np

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    for i in TD:
        if not type_count_dict.get(i[0]):
            type_count_dict[i[0]] = 0
    #  print(type_count_dict)

    S = TD[:K]
    #  print('S', S)
    for i in S:
        type_count_dict[i[0]] += 1

    #  print('type_count', type_count_dict)
    base_point = sum(i[1] for i in S)
    type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    done_types = []
    #  print('type_count_dict', type_count_dict)
    for i in TD[K:]:
        if i[0] in done_types:
            continue
        if type_count_dict[i[0]] == 0:
            remaining_items.append(i[1])
            done_types.append(i[0])
    #  print('remaining_items', remaining_items)

    ridx = 0
    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) == 0:
            break
        if type_count_dict[s[0]] >= 2:
            # print('s', s)
            type_count_dict[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            type_bonus += 1
            ridx += 1
            results.append(type_bonus**2 + base_point)

    print(max(results))
   

main()

Submission status: Runtime Error

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
#  import numpy as np

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    TD = sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    #  print(TD)
    # 種類のカウントをもつ
    type_count_dict = {}
    for i in TD:
        if not type_count_dict.get(i[0]):
            type_count_dict[i[0]] = 0
    #  print(type_count_dict)

    S = TD[:K]
    #  print('S', S)
    for i in S:
        type_count_dict[i[0]] += 1

    #  print('type_count', type_count_dict)
    base_point = sum(i[1] for i in S)
    type_bonus = len(set([i[0] for i in S]))
    result = base_point + type_bonus**2
    results = [result]
    #  print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    remaining_items = queue.PriorityQueue()
    done_types = []
    #  print('type_count_dict', type_count_dict)
    for i in TD[K:]:
        if i[0] in done_types:
            continue
        if type_count_dict[i[0]] == 0:
            #  remaining_items.append(i[1])
            remaining_items.put(i[1])
            done_types.append(i[0])
    #  print('remaining_items', remaining_items)

    ridx = 0
    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) == 0:
            break
        if type_count_dict[s[0]] >= 2:
            # print('s', s)
            type_count_dict[s[0]] -= 1
            base_point += remaining_items[ridx] - s[1]
            type_bonus += 1
            ridx += 1
            results.append(type_bonus**2 + base_point)

    print(max(results))
   

main()

Submission status: Runtime Error

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
#  import numpy as np

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    # print(TD)
    # 種類のカウントをもつ
    #  print(max(TD, key=lambda x:x[1]))
    type_count = [0 for i in range(max(TD, key=lambda x:x[1])[1] + 1)]

    S = TD[:K]
    # print('S', S)
    for i in S:
        type_count[i[0]] += 1

    # print('type_count', type_count)
    base_point = sum(i[1] for i in S)
    type_bonus = len([i for i in type_count if i != 0])
    result = base_point + type_bonus**2
    results = [result]
    # print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    remaining_items = []
    done_types = []
    for i in TD[K:]:
        if i[0] in done_types:
            continue
        if type_count[i[0]] == 0:
            remaining_items.append(i[1])
            done_types.append(i[0])
    # print('remaining_items', remaining_items)

    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) == 0:
            break
        if type_count[s[0]] >= 2:
            # print('s', s)
            type_count[s[0]] -= 1
            base_point += remaining_items[0] - s[1]
            #  S[len(S) - 1 - idx] = TD[remaining_items[0]]
            type_bonus += 1
            # print('base_point1', base_point)
            # print('base_point2', base_point)
            # print('type_bonus', type_bonus)
            del remaining_items[0]
            results.append(type_bonus**2 + base_point)

    print(max(results))
    
main()

Submission status: Runtime Error

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

N,K=rl()

td_1 = [0]*N
td_rem = []
for _ in range(N):
    t,d = rl()
    t -= 1
    if td_1[t] == 0:
        td_1[t] = d
    else:
        if d <= td_1[t]:
            td_rem += [d]
        else:
            td_rem += [td_1[t]]
            td_1[t] = d


td_1.sort(reverse=True)
td_rem.sort(reverse=True)
#print(td_1)
#print(td_rem)
import numpy as np
td_1 = list(np.cumsum([0] + td_1[:td_1.index(0)]))
td_rem = list(np.cumsum([0]+td_rem))

ans = [0 for _ in range(K+1)]
sum_l = 0
for i in range(1,K+1):
    if len(td_1)-1 >= i and len(td_rem)-1>=K-i:
        ans[i] = i*i + td_1[i] + td_rem[K-i]

#print(td_1)
#print(td_rem)
#print(ans)
print(max(ans))

Submission status: Runtime Error

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

N,K=rl()

td_1 = [0]*N
td_rem = []
for _ in range(N):
    t,d = rl()
    t -= 1
    if td_1[t] == 0:
        td_1[t] = d
    else:
        if d <= td_1[t]:
            td_rem += [d]
        else:
            td_rem += [td_1[t]]
            td_1[t] = d


td_1.sort(reverse=True)
td_rem.sort(reverse=True)
#print(td_1)
#print(td_rem)
import numpy as np
td_1 = np.cumsum([0] + td_1[:td_1.index(0)])
td_rem = np.cumsum([0]+td_rem)

ans = [0 for _ in range(K+1)]
sum_l = 0
for i in range(1,K+1):
    if len(td_1)-1 >= i and len(td_rem)-1>=K-i:
        ans[i] = i*i + td_1[i] + td_rem[K-i]

#print(td_1)
#print(td_rem)
#print(ans)
print(max(ans))

Submission status: Runtime Error

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

N,K=rl()

td_1 = [0]*N
td_rem = []
for i in range(N):
    t,d = rl()
    t -= 1
    if td_1[t] == 0:
        td_1[t] = d
    else:
        if d <= td_1[t]:
            td_rem += [d]
        else:
            td_rem += td_1[t]
            td_1[t] = d


td_1.sort(reverse=True)
td_rem.sort(reverse=True)

ans = [0 for _ in range(K+1)]
sum_l = 0
for i in range(1,K+1):
    if td_1[i-1] != 0 and len(td_rem)>=K-i:
        ans[i] = i*i + sum(td_1[:i]) + sum(td_rem[:(K-i)])

#print(td_1)
#print(td_rem)
#print(ans)
print(max(ans))

Submission status: Runtime Error

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

N,K=rl()

td_1 = [0]*N
td_rem = []
for i in range(N):
    t,d = rl()
    t -= 1
    if td_1[t] == 0:
        td_1[t] = d
    else:
        if d <= td_1[t]:
            td_rem += [d]
        else:
            td_rem += td_1[t]
            td_1[t] = [d]


td_1.sort(reverse=True)
td_rem.sort(reverse=True)

ans = [0 for _ in range(K+1)]
sum_l = 0
for i in range(1,K+1):
    if td_1[i-1] != 0 and len(td_rem)>=K-i:
        ans[i] = i*i + sum(td_1[:i]) + sum(td_rem[:(K-i)])

#print(td_1)
#print(td_rem)
#print(ans)
print(max(ans))

Submission status: Runtime Error

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
#  import numpy as np

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N, K = LI()
    T = []
    D = []
    TD = []
    [TD.append(LI()) for i in range(N)]
    # sort desc
    #  TD = np.array(TD)
    #  TD = TD[np.argsort(TD[:, 1])[::-1]]
    sorted(TD, key=lambda l:l[1], reverse=True)
    #  print(TD)

    # print(TD)
    # 種類のカウントをもつ
    #  print(max(TD, key=lambda x:x[1]))
    type_count = [0 for i in range(max(TD, key=lambda x:x[1])[1] + 1)]

    S = TD[:K]
    # print('S', S)
    for i in S:
        type_count[i[0]] += 1

    # print('type_count', type_count)
    base_point = sum(i[1] for i in S)
    type_bonus = len([i for i in type_count if i != 0])
    result = base_point + type_bonus**2
    results = [result]
    # print('base_point, type_bonus, result', base_point, type_bonus**2, result)

    remaining_items = []
    done_types = []
    for i in TD[K:]:
        if i[0] in done_types:
            continue
        if type_count[i[0]] == 0:
            remaining_items.append(i[1])
            done_types.append(i[0])
    # print('remaining_items', remaining_items)

    for idx, s in enumerate(S[::-1]):
        if len(remaining_items) == 0:
            break
        if type_count[s[0]] >= 2:
            # print('s', s)
            type_count[s[0]] -= 1
            base_point -= s[1]
            #  S[len(S) - 1 - idx] = TD[remaining_items[0]]
            type_bonus += 1
            # print('base_point1', base_point)
            base_point += remaining_items[0]
            # print('base_point2', base_point)
            # print('type_bonus', type_bonus)
            del remaining_items[0]
            results.append(type_bonus**2 + base_point)

    print(max(results))
    
main()