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

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 = {}
    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:
                type_bonus += 1
            type_count_dict[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:
            #  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:
            # print('s', s)
            type_count_dict[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)

    print(max(results))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#  import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import sys
#  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 = {}
    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:
                type_bonus += 1
            type_count_dict[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 = []
    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) < ridx + 1:
            break
        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))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#  import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import sys
#  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 = {}
    base_point = 0
    for idx, i in enumerate(TD):
        if not type_count_dict.get(i[0]):
            type_count_dict[i[0]] = 0
        if idx < K:
            type_count_dict[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 = []
    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) < ridx + 1:
            break
        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))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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 = {}
    base_point = 0
    for idx, i in enumerate(TD):
        if not type_count_dict.get(i[0]):
            type_count_dict[i[0]] = 0
        if idx < K:
            type_count_dict[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 = []
    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) < ridx + 1:
            break
        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))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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)
    base_point = 0
    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 = []
    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) < ridx + 1:
            break
        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))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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) < ridx + 1:
            break
        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))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
#  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 = {}
    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 = []
    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:
            #  remaining_items.append(i[1])
            remaining_items.put((-i[1], i[1]))
            done_types.append(i[0])

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

    print(max(results))


main()

Submission status: Time Limit Exceeded

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) < ridx + 1:
            break
        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: Time Limit Exceeded

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)

    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[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]
            #  print(type_bonus)
            results.append(type_bonus**2 + base_point)

    print(max(results))
    
main()

Submission status: Time Limit Exceeded

Solution code:
#-*- coding: utf-8 -*-
"""
oj dl https://atcoder.jp/contests/abc116/tasks/abc116_d -d test-d
oj test -d test-d -c "python abc116d.py"
oj test -d test-d -c "python abc116d.py" test-d/sample-3.in
"""

from collections import defaultdict
import sys
import time


def deco(func):
    def wrapper(*args, **kwargs):
        s = time.time()
        #print('--start--')
        ret = func(*args, **kwargs)
        logging.debug('--end in %f --' % (time.time() - s))
        return ret

    return wrapper


import itertools
#@deco
def sol(n, k, S):
    maxi = 0
    for comb in itertools.combinations(S, k):
        neta = defaultdict(int)
        ttl = 0
        for t, d in comb:
            ttl += d
            neta[t] += 1
        ttl += len(neta)**2
        maxi = max(maxi, ttl)
    return maxi


import logging

#logging.basicConfig(level=logging.DEBUG, format="%(message)s")
logging.basicConfig(level=logging.ERROR, format="%(message)s")
do_submit = True
#do_submit = False
def input_parse(input_str):
    lines = [x.strip() for x in input_str.split("\n") if x.strip()]
    parsed_lines = [list(map(int, line.split())) for line in lines]
    n, k = parsed_lines[0]
    S = []
    for i in range(n):
        t, d = parsed_lines[i+1]
        S.append((t, d))
    return (n, k, S)


if not do_submit:
    n, k, S = input_parse("""
    5 3
    1 9
    1 7
    2 6
    2 5
    3 1
    """)
    print(sol(n, k, S))
else:
    n, k = list(map(int, input().split()))
    S = []
    for i in range(n):
        t, d = list(map(int, input().split()))
        S.append((t, d))
    print(sol(n, k, S))

Submission status: Time Limit Exceeded

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)

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

Solution code:
import heapq

n, k = [int(x) for x in input().split()]

data = [[int(x) for x in input().split()] for _ in range(n)]
data.sort(reverse=True, key=lambda x: x[1])

eat = {}
noeat = {}

for x in data[0:k]:
  if x[0] in eat:
    heapq.heappush(eat[x[0]], x[1])
  else:
    eat[x[0]] = [x[1]]

for x in data[k:]:
  if x[0] in noeat:
    heapq.heappush(noeat[x[0]], -x[1])
  else:
    noeat[x[0]] = [-x[1]]

max_score = 0

while True:
  #print(eat)
  #print(noeat)
  score = 0
  for x in eat:
    score += sum(eat[x])
  score += len(eat)**2
  if max_score < score:
    max_score = score
  remove = None
  min_score1 = 10**12+1
  for x in eat:
    if 1 < len(eat[x]) and eat[x][0] < min_score1:
      remove = x
      min_score1 = eat[x][0]
  add = None
  max_score1 = 0
  for x in noeat:
    if max_score1 < -noeat[x][0] and not(x in eat):
      add = x
      max_score1 = -noeat[x][0]
  if remove == None or add == None:
    break
  else:
    eat[add] = [max_score1]
    heapq.heappop(eat[remove])
    if 1 < len(noeat[add]):
      heapq.heappop(noeat[add])
    else:
      noeat.pop(add)

print(max_score)

Submission status: Time Limit Exceeded

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]]

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

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

    # print('type_count', type_count)
    base_point = np.sum(S[:, 1])
    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()