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:
n, k = [int(i) for i in input().split(" ")]
t = []
d = []

for i in range(0, n):
    x, y = [int(i) for i in input().split(" ")]
    t.append(x)
    d.append(y)

dt = zip(d, t)
dt = sorted(dt, key = lambda k:k[0], reverse=True)
td = [[] for i in range(0, n + 1)]
tp = []
dp = [[0 for j in range(0, k)] for i in range(0, k)]
eaten = [[0 for j in range(0, k)] for i in range(0, k)]

for i in range(0, n):
    td[dt[i][1]].append(dt[i][0])
    if len(td[dt[i][1]]) == 1:
        tp.append(dt[i][1])

dp[0][0] = td[tp[0]][0] + 1
eaten[0][0] = 1

for j in range(1, k):
    if eaten[0][j - 1] < len(td[tp[0]]):
        dp[0][j] = dp[0][j - 1] + td[tp[0]][eaten[0][j - 1]]
        eaten[0][j] = eaten[0][j - 1] + 1
    else:
        break


for i in range(1, len(tp)):
    eaten[i][i] = 1
    dp[i][i] =  dp[i - 1][i - 1] + td[tp[i]][0] + 2 * i + 1
    for j in range(i + 1, k):
        if dp[i - 1][j - 1] == 0 or (eaten[i][j - 1] < len(td[tp[i]]) and 2 * i + 1 + td[tp[i]][0] < td[tp[i]][eaten[i][j - 1]]):
            if eaten[i][j - 1] < len(td[tp[i]]) and dp[i][j - 1] > 0:
                dp[i][j] = dp[i][j - 1] + td[tp[i]][eaten[i][j - 1]]
                eaten[i][j] = eaten[i][j - 1] + 1
        else:
            if dp[i - 1][j - 1] > 0:
                dp[i][j] = dp[i - 1][j - 1] + 2 * i + 1 + td[tp[i]][0]
                eaten[i][j] = 1

print(max([i[-1] for i in dp]))

Submission status: Runtime Error

Solution code:
n, k = [int(i) for i in input().split(" ")]
t = []
d = []

for i in range(0, n):
    x, y = [int(i) for i in input().split(" ")]
    t.append(x)
    d.append(y)
    
dt = zip(d, t)
dt = sorted(dt, key = lambda k:k[0], reverse=True)
td = [[] for i in range(0, n + 1)]
tp = []
dp = [[0 for j in range(0, k)] for i in range(0, k)]
eaten = [[0 for j in range(0, k)] for i in range(0, k)]

for i in range(0, n):
    td[dt[i][1]].append(dt[i][0])
    if len(td[dt[i][1]]) == 1:
        tp.append(dt[i][1])

dp[0][0] = td[tp[0]][0] + 1
eaten[0][0] = 1

for j in range(1, k):
    if eaten[0][j - 1] < len(td[tp[0]]):
        dp[0][j] = dp[0][j - 1] + td[tp[0]][eaten[0][j - 1]]
        eaten[0][j] = eaten[0][j - 1] + 1
    else:
        break


for i in range(1, k):
    eaten[i][i] = 1
    dp[i][i] =  dp[i - 1][i - 1] + td[tp[i]][0] + 2 * i + 1
    for j in range(i + 1, k):
        if dp[i - 1][j - 1] == 0 or (eaten[i][j - 1] < len(td[tp[i]]) and 2 * i + 1 + td[tp[i]][0] < td[tp[i]][eaten[i][j - 1]]):
            if eaten[i][j - 1] < len(td[tp[i]]) and dp[i][j - 1] > 0:
                dp[i][j] = dp[i][j - 1] + td[tp[i]][eaten[i][j - 1]]
                eaten[i][j] = eaten[i][j - 1] + 1
        else:
            if dp[i - 1][j - 1] > 0:
                dp[i][j] = dp[i - 1][j - 1] + 2 * i + 1 + td[tp[i]][0]
                eaten[i][j] = 1

print(max([i[-1] for i in dp]))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
TD = []
for _ in range(N):
    TD.append(list(map(int, input().split())))
TD.sort(key=lambda x: -x[1])

tmp_list = TD[:K]
removable_list = []
S = set()
base_pt = 0
for t, d in tmp_list:
    if t in S:
        removable_list.append([t, d])
    else:
        S.add(t)
    base_pt += d
kind = len(S)
removable_list.sort(key=lambda x: x[1])

pt = [base_pt + kind*kind]
i = 0
for t, d in TD[K:]:
    if t in S:
        continue
    kind += 1
    base_pt += d - removable_list[i][1]
    pt.append(base_pt + kind*kind)
    i += 1
print(max(pt))

Submission status: Runtime Error

Solution code:
import heapq
n,k=map(int,input().split())
data=[]
for i in range(n):
    t,d=map(int,input().split())
    data.append((-d,t))
data=sorted(data)
neta=set()
que1=[]
que2=[]
p,x=0,0
for i in range(k):
    if data[i][1] in neta:
        heapq.heappush(que1,data[i])
        x-=data[i][0]
    else:
        x-=data[i][0]
        p+=1
        neta.add(data[i][1])
for i in range(k,n):
    if data[i][1]in neta:
        pass
    else:
        heapq.heappush(que2,data[i])
mx=x+p*p
while que1:
    a=heapq.heappop(que1)
    b==None
    while que2:
        b=heapq.heappop(que2)
        if b[1] not in neta:
            break
        b=None
    if b==None:
        break
    x=x+a[0]-b[0]
    p+=1
    neta.add(b[1])
    mx=max(mx,x+p*p)
print(mx)

Submission status: Runtime Error

Solution code:
import heapq
n,k=map(int,input().split())
data=[]
for i in range(n):
    t,d=map(int,input().split())
    data.append((-d,t))
data=sorted(data)
neta=set()
que1=[]
que2=[]
p,x=0,0
for i in range(k):
    if data[i][1] in neta:
        heapq.heappush(que1,data[i])
        x-=data[i][0]
    else:
        x-=data[i][0]
        p+=1
        neta.add(data[i][1])
for i in range(k,n):
    if data[i][1]in neta:
        pass
    else:
        heapq.heappush(que2,data[i])
mx=x+p*p
while que1:
    a=heapq.heappop(que1)
    while que2:
        b=heapq.heappop(que2)
        if b[1] not in neta:
            break
        b=None
    if b==None:
        break
    x=x+a[0]-b[0]
    p+=1
    neta.add(b[1])
    mx=max(mx,x+p*p)
print(mx)

Submission status: Runtime Error

Solution code:
import heapq
n,k=map(int,input().split())
data=[]
for i in range(n):
    t,d=map(int,input().split())
    data.append((-d,t))
data=sorted(data)
neta=set()
que1=[]
que2=[]
p,x=0,0
for i in range(k):
    if data[i][1] in neta:
        heapq.heappush(que1,data[i])
        x-=data[i][0]
    else:
        x-=data[i][0]
        p+=1
        neta.add(data[i][1])
for i in range(k,n):
    if data[i][1]in neta:
        pass
    else:
        heapq.heappush(que2,data[i])
mx=x+p*p
tmp=x+p*p
while que1:
    a=heapq.heappop(que1)
    while que2:
        b=heapq.heappop(que2)
        if b[1] not in neta:
            break
    tmp=(tmp-p*p)+a[0]-b[0]+(p+1)**2
    p+=1
    neta.add(b[1])
    mx=max(mx,tmp)
print(mx)

Submission status: Runtime Error

Solution code:
import heapq
n,k=map(int,input().split())
data=[]
for i in range(n):
    t,d=map(int,input().split())
    data.append((-d,t))
data=sorted(data)
neta=set()
que1=[]
que2=[]
p,x=0,0
for i in range(k):
    if data[i][1] in neta:
        heapq.heappush(que1,data[i])
        x-=data[i][0]
    else:
        x-=data[i][0]
        p+=1
        neta.add(data[i][1])
for i in range(k,n):
    if data[i][1]in neta:
        pass
    else:
        heapq.heappush(que2,data[i])
mx=x+p*p
tmp=x+p*p
while que1:
    a=heapq.heappop(que1)
    while True:
        b=heapq.heappop(que2)
        if b[1] not in neta:
            break
    tmp=(tmp-p*p)+a[0]-b[0]+(p+1)**2
    p+=1
    neta.add(b[1])
    mx=max(mx,tmp)
print(mx)

Submission status: Runtime Error

Solution code:
N,K = list(map(int,input().split()))
TDlist = []

for x in range(0,N):
    TDlist.append(list(map(int,input().split())))

TDlist.reverse(key = lambda x: x[1])
kinds = []
seconds = []
answer = 0

for x in TDlist[:K]:
    if not x[0] in kinds:
        kinds.append(x[0])
    else:
        seconds.append(x[1])
    answer += x[1]

answer += len(kinds)**2
score = answer
max_score = answer

for x in TDlist[K:]:
    if seconds == []:
        break
    if x[0] in kinds:
        continue
    kinds.append(x[0])
    y = seconds.pop()
    score += (x[1] - y) + (len(kinds)*2 -1)
    max_score = max(score,answer)
    

answer = max(answer,max_score)

print(answer)

Submission status: Runtime Error

Solution code:
N,K = list(map(int,input().split()))
TDlist = []

for x in range(0,N):
    TDlist.append(list(map(int,input().split())))

sorted_list = sorted(TDlist, key = lambda x: x[1], reverse=True)
kinds = []
seconds = []
answer = 0

for x in range(0,K):
    if not sorted_list[x][0] in kinds:
        kinds.append(sorted_list[x][0])
    else:
        seconds.append(sorted_list[x][1])
    answer += sorted_list[x][1]

answer += len(kinds)**2
score = answer
max_score = answer

for x in range(K,N):
    if seconds is []:
        break
    if sorted_list[x][0] in kinds:
        continue
    kinds.append(sorted_list[x][0])
    score += (sorted_list[x][1] - seconds[-1]) + (len(kinds)*2 -1)
    max_score = max(score,answer)
    seconds.pop()

answer = max(answer,max_score)

print(answer)

Submission status: Runtime Error

Solution code:
S = list(map(int,input().split()))
N = S[0]
K = S[1]
TDlist = []
for x in range(0,N):
    TDlist.append(list(map(int,input().split())))

sorted_list = sorted(TDlist, key = lambda x: x[1], reverse=True)
kinds = []
seconds =[]
answer = 0

for x in range(0,K):
    if not sorted_list[x][0] in kinds:
        kinds.append(sorted_list[x][0])
    else:
        seconds.append(sorted_list[x][1])
    answer += sorted_list[x][1]

answer += len(kinds)**2
score = answer
max_score = answer

for x in range(K,N):
    if seconds is []:
        break
    if sorted_list[x][0] in kinds:
        continue
    kinds.append(sorted_list[x][0])
    score += (sorted_list[x][1] - seconds[-1]) + (len(kinds)*2 -1)
    max_score = max(score,answer)

answer = max(answer,max_score)

print(answer)

Submission status: Runtime Error

Solution code:
S = list(map(int,input().split()))
N = S[0]
K = S[1]
TDlist = []
for x in range(0,N):
    T = list(map(int,input().split()))
    TDlist.append(T)

sorted_list = sorted(TDlist, key = lambda x: x[1], reverse=True)
kinds = []
seconds =[]
answer = 0

for x in range(0,K):
    if not sorted_list[x][0] in kinds:
        kinds.append(sorted_list[x][0])
    else:
        seconds.append(sorted_list[x][1])
    answer += sorted_list[x][1]

answer += len(kinds)**2
score = answer

for x in range(K,N):
    if seconds is []:
        break
    if sorted_list[x][0] in kinds:
        continue
    kinds.append(sorted_list[x][0])
    score += (sorted_list[x][1] - seconds[-1]) + (len(kinds)*2 -1)
    max_score = max(score,answer)

answer = max(answer,max_score)

print(answer)

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush, heapify

N, K = map(int, input().split())
sushi = [(-d, t) for t, d in map(int, input().split())]
heapify(sushi)

maxs = []
rems = []
kinds = set()
for _ in range(K):
    d, t = heappop(sushi)
    if t in kinds:
        heappush(rems, -d)
    else:
        maxs.append(-d)
        kinds.add(t)
ans = sum(maxs) + sum(rems) + len(kinds)**2

while True:
    if not sushi or not rems:
        break
    d, t = heappop(sushi)
    if t in kinds:
        continue
    else:
        heappop(rems)
        maxs.append(-d)
        kinds.add(t)
        ans = max(ans, sum(maxs) + sum(rems) + len(kinds)**2)

print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush

N, K = map(int, input().split())
sushi = []
for _ in range(N):
    t, d = map(int, input().split())
    heappush(sushi, (-d, t))

maxs = []
rems = []
kinds = set()
for _ in range(K):
    d, t = heappop(sushi)
    if t in kinds:
        heappush(rems, -d)
    else:
        maxs.append(-d)
        kinds.add(t)
ans = sum(maxs) + sum(rems) + len(kinds)**2

while True:
    if not rems:
        break
    d, t = heappop(sushi)
    if t in kinds:
        continue
    else:
        heappop(rems)
        maxs.append(-d)
        kinds.add(t)
        ans = max(ans, sum(maxs) + sum(rems) + len(kinds)**2)

print(ans)

Submission status: Runtime Error

Solution code:
from itertools import groupby
from heapq import heapify, heappop

N, K = map(int, input().split())
sushi = [tuple(map(int, input().split())) for _ in range(N)]

srt = sorted(sushi, key=lambda x: x[1], reverse=True)
eat, non_eat = srt[:K], srt[K:]

maxs = []
rems = []
kinds = set()
for k, g in groupby(sorted(eat, key=lambda x: x[0]), key=lambda x: x[0]):
    d = list(list(zip(*g))[1])
    maxs.append(d.pop(0))
    rems.extend(d)
    kinds.add(k)
heapify(rems)
ans = sum(maxs) + sum(rems) + len(kinds)**2

for k, g in groupby(sorted(non_eat, key=lambda x: x[0]), key=lambda x: x[0]):
    if k in kinds:
        continue
    d = list(list(zip(*g))[1])
    maxs.append(d.pop(0))
    heappop(rems)
    kinds.add(k)
    ans = max(ans, sum(maxs) + sum(rems) + len(kinds)**2)

print(ans)

Submission status: Runtime Error

Solution code:
from itertools import groupby
from heapq import heapify, heappop

N, K = map(int, input().split())
sushi = [tuple(map(int, input().split())) for _ in range(N)]


def point(sushi):
    t, d = zip(*sushi)
    return sum(d) + len(set(t))**2


srt = sorted(sushi, key=lambda x: x[1], reverse=True)
eat, non_eat = srt[:K], srt[K:]

maxs = []
rems = []
kinds = set()
for k, g in groupby(sorted(eat, key=lambda x: x[0]), key=lambda x: x[0]):
    _, d = zip(*g)
    maxs.append(d.pop(0))
    rems.extend(d)
    kinds.add(k)
heapify(rems)
ans = point(eat)

for k, g in groupby(sorted(non_eat, key=lambda x: x[0]), key=lambda x: x[0]):
    if k in kinds:
        continue
    _, d = zip(*g)
    maxs.append(d.pop(0))
    heappop(rems)
    kinds.add(k)
    ans = max(ans, point(maxs + rems))

print(ans)

Submission status: Runtime Error

Solution code:
from itertools import groupby

N, K = map(int, input().split())
sushi = sorted([tuple(map(int, input().split())) for _ in range(N)],
               key=lambda s: s[1])

maximums = []
remains = []
v = set()
for k, g in groupby(sushi[-K:], key=lambda x: x[0]):
    v.add(k)
    ds = list(list(zip(*g))[1])
    maximums.append(ds.pop())
    remains.extend(ds)
remains = sorted(remains)
ans = sum(maximums) + sum(remains) + len(v)**2

max_v = max(K, len(set(list(zip(*sushi))[0])))

for k, g in groupby(sorted(sushi[:-K], key=lambda x: x[0]), key=lambda x: x[0]):
    if k in v:
        continue
    v.add(k)
    ds = list(list(zip(*g))[1])
    maximums.append(ds.pop())
    remains.pop()
    ans = max(ans, sum(maximums) + sum(remains) + len(v)**2)

print(ans)

Submission status: Runtime Error

Solution code:
import itertools
def point_calc():
    
    n, k = map(int, input().split())
    kind, taste = [], []
    kind_point, taste_point = [], []

    for i in range(n): # 入力を読み取る
        kind_tmp, taste_tmp = map(int, input().split())
        kind.append(kind_tmp)
        taste.append(taste_tmp)
    
    a = list(itertools.permutations(taste, k))
    b = list(itertools.permutations(kind, k))
    
    for i in range(len(a)):
        taste_point.append(sum(a[i]))
        kind_point.append(pow(len(np.unique(b[i])),2))
    
    total_point = [a + b for a, b in zip(taste_point, kind_point)]
    return total_point

if __name__ == "__main__":
    point = max(point_calc())
    print(point)

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():
    # 問題をdfs的手法で解いてみる
    N, K = LI()
    T = []
    D = []
    TD = []
    for i in range(N):
        TD.append(LI())
    TD = np.array(TD)
    # print(TD)
    TD = TD[np.argsort(TD[:, 1])[::-1]]

    neta_type_list = set([i[0] for i in TD])

    # print("neta_type, TD\n", neta_type_list, TD)
    result = 0
    for k in range(1, K+1):
        if k > len(neta_type_list):
            break
        # 1種類の場合のみ分けて考える
        if k == 1:
            result = sum([i[1] for i in TD[:K]]) + 1
            continue
        # k種類選ぶ場合を考える
        # タイプごとのカウントを保持する
        # print('\n=====k種類選ぶ場合', k, k*k)
        result = max(result, find_max_combi_value(neta_type_list, TD, k, K) + k*k)

    print(result)


def find_max_combi_value(neta_type_list, TD, k, K):
        c = 0
        type_count = [[i, 0] for i in neta_type_list]
        result = 0
        # そもそも組み合わせが作れない場合
        type_length_list = np.zeros(max([i[0] for i in TD]) + 1)
        for i in TD:
            type_length_list[i[0]] += 1
        # print(type_length_list)
        type_length_list = np.sort(type_length_list)[::-1]
        # print(type_length_list)
        if sum(type_length_list[:k]) < K:
            return 0

        while True:
            # print('\nc', c)
            # print('while type-count', type_count)
            # まず種類分確保しなくてはいけない
            # print('TD[c]\n', TD[c])
            old_type_count = copy.copy(type_count)
            # print('initial, 999909909', old_type_count, type_count)

            for idx, i in enumerate(type_count):
                try:
                    if i[0] == TD[c][0]:
                        type_count[idx][1] += 1
                except:
                    import pdb
                    pdb.set_trace()
            type_count = np.array(type_count)
            type_count = type_count[np.argsort(type_count[:, 1])[::-1]]
            result += TD[c][1]
            # i個最大のものをとって、Kに達していたら終了
            if type_count[0][1] > K - k + 1:
                # print('111111', old_type_count)
                type_count = copy.copy(old_type_count)
                result -= TD[c][1]
                # print('result0', result)
                c += 1
                continue

            # ちょうどK個選んだ場合
            # print('選んだ個数合計', sum([i[1] for i in type_count[:k]]))
            if sum([i[1] for i in type_count[:k]]) == K:
                # 0がある場合はだめ
                if any([i[1] == 0 for i in type_count[:k]]):
                    # print('======', c, type_count)
                    result -= TD[c][1]
                    type_count = copy.copy(old_type_count)
                    # print('result1', result)
                    c += 1
                    continue
                # print('end type-count\n', type_count)
                return result
            if c == len(TD)-1:
                return 0
            # print('type_count ending', type_count)
            # print('result2', result)
            old_type_count = copy.copy(type_count)
            c += 1


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():
    # 問題をdfs的手法で解いてみる
    N, K = LI()
    T = []
    D = []
    TD = []
    for i in range(N):
        TD.append(LI())
    TD = np.array(TD)
    # print(TD)
    TD = TD[np.argsort(TD[:, 1])[::-1]]

    neta_type_list = set([i[0] for i in TD])

    # print("neta_type, TD\n", neta_type_list, TD)
    result = 0
    for k in range(1, K+1):
        # 1種類の場合のみ分けて考える
        if k == 1:
            result = TD[0][1] + 1
            continue
        # k種類選ぶ場合を考える
        # タイプごとのカウントを保持する
        # print('\n=====k種類選ぶ場合', k, k*k)
        result = max(result, find_max_combi_value(neta_type_list, TD, k, K) + k*k)

    print(result)


def find_max_combi_value(neta_type_list, TD, k, K):
        c = 0
        type_count = [[i, 0] for i in neta_type_list]
        result = 0
        # そもそも組み合わせが作れない場合
        type_length_list = np.zeros(max([i[0] for i in TD]) + 1)
        for i in TD:
            type_length_list[i[0]] += 1
        # print(type_length_list)
        type_length_list = np.sort(type_length_list)[::-1]
        # print(type_length_list)
        if sum(type_length_list[:k]) < K:
            return 0

        while True:
            # print('\nc', c)
            # print('while type-count', type_count)
            # まず種類分確保しなくてはいけない
            # print('TD[c]\n', TD[c])
            old_type_count = copy.copy(type_count)
            # print('initial, 999909909', old_type_count, type_count)

            for idx, i in enumerate(type_count):
                try:
                    if i[0] == TD[c][0]:
                        type_count[idx][1] += 1
                except:
                    import pdb
                    pdb.set_trace()
            type_count = np.array(type_count)
            type_count = type_count[np.argsort(type_count[:, 1])[::-1]]
            result += TD[c][1]
            # i個最大のものをとって、Kに達していたら終了
            if type_count[0][1] > K - k + 1:
                # print('111111', old_type_count)
                type_count = copy.copy(old_type_count)
                result -= TD[c][1]
                # print('result0', result)
                c += 1
                continue

            # ちょうどK個選んだ場合
            # print('選んだ個数合計', sum([i[1] for i in type_count[:k]]))
            if sum([i[1] for i in type_count[:k]]) == K:
                # 0がある場合はだめ
                if any([i[1] == 0 for i in type_count[:k]]):
                    # print('======', c, type_count)
                    result -= TD[c][1]
                    type_count = copy.copy(old_type_count)
                    # print('result1', result)
                    c += 1
                    continue
                # print('end type-count\n', type_count)
                return result
            if c == len(TD)-1:
                return 0
            # print('type_count ending', type_count)
            # print('result2', result)
            old_type_count = copy.copy(type_count)
            c += 1


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():
    # 問題をdfs的手法で解いてみる
    N, K = LI()
    T = []
    D = []
    TD = []
    for i in range(N):
        TD.append(LI())
    TD = np.array(TD)
    # print(TD)
    TD = TD[np.argsort(TD[:, 1])[::-1]]

    neta_type_list = set([i[0] for i in TD])

    # print("neta_type, TD\n", neta_type_list, TD)
    result = 0
    for k in range(1, K+1):
        # 1種類の場合のみ分けて考える
        if k == 1:
            result = TD[0][1] + 1
            continue
        # k種類選ぶ場合を考える
        # タイプごとのカウントを保持する
        # print('\n=====k種類選ぶ場合', k, k*k)
        result = max(result, find_max_combi_value(neta_type_list, TD, k, K) + k*k)

    print(result)


def find_max_combi_value(neta_type_list, TD, k, K):
        c = 0
        type_count = [[i, 0] for i in neta_type_list]
        result = 0
        # そもそも組み合わせが作れない場合
        type_length_list = np.zeros(max([i[0] for i in TD]) + 1)
        for i in TD:
            type_length_list[i[0]] += 1
        # print(type_length_list)
        type_length_list = np.sort(type_length_list)[::-1]
        # print(type_length_list)
        if sum(type_length_list[:k]) < K:
            return 0

        while True:
            # print('\nc', c)
            # print('while type-count', type_count)
            # まず種類分確保しなくてはいけない
            # print('TD[c]\n', TD[c])
            old_type_count = copy.copy(type_count)
            # print('initial, 999909909', old_type_count, type_count)

            for idx, i in enumerate(type_count):
                if i[0] == TD[c][0]:
                    type_count[idx][1] += 1
            type_count = np.array(type_count)
            type_count = type_count[np.argsort(type_count[:, 1])[::-1]]
            result += TD[c][1]
            # i個最大のものをとって、Kに達していたら終了
            if type_count[0][1] > K - k + 1:
                # print('111111', old_type_count)
                type_count = copy.copy(old_type_count)
                result -= TD[c][1]
                # print('result0', result)
                c += 1
                continue

            # ちょうどK個選んだ場合
            # print('選んだ個数合計', sum([i[1] for i in type_count[:k]]))
            if sum([i[1] for i in type_count[:k]]) == K:
                # 0がある場合はだめ
                if any([i[1] == 0 for i in type_count[:k]]):
                    # print('======', c, type_count)
                    result -= TD[c][1]
                    type_count = copy.copy(old_type_count)
                    # print('result1', result)
                    c += 1
                    continue
                # print('end type-count\n', type_count)
                return result
            if c == len(TD-1):
                return 0
            # print('type_count ending', type_count)
            # print('result2', result)
            old_type_count = copy.copy(type_count)
            c += 1


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():
    # 問題をdfs的手法で解いてみる
    N, K = LI()
    T = []
    D = []
    TD = []
    for i in range(N):
        TD.append(LI())
    TD = np.array(TD)
    # print(TD)
    TD = TD[np.argsort(TD[:, 1])[::-1]]

    neta_type_list = set([i[0] for i in TD])

    # print("neta_type, TD\n", neta_type_list, TD)
    result = 0
    if K == 0:
        print(0)
        return

    for k in range(1, K+1):
        # 1種類の場合のみ分けて考える
        if k == 1:
            result = max([t[1] for t in TD])
            continue
        # k種類選ぶ場合を考える
        # タイプごとのカウントを保持する
        # print('\n=====k種類選ぶ場合', k, k*k)
        result = max(result, find_max_combi_value(neta_type_list, TD, k, K) + k*k)

    print(result)


def find_max_combi_value(neta_type_list, TD, k, K):
        c = 0
        type_count = [[i, 0] for i in neta_type_list]
        result = 0
        # そもそも組み合わせが作れない場合
        type_length_list = np.zeros(max([i[0] for i in TD]) + 1)
        for i in TD:
            type_length_list[i[0]] += 1
        # print(type_length_list)
        type_length_list = np.sort(type_length_list)[::-1]
        # print(type_length_list)
        if sum(type_length_list[:k]) < K:
            return 0

        while True:
            # print('\nc', c)
            # print('while type-count', type_count)
            # まず種類分確保しなくてはいけない
            # print('TD[c]\n', TD[c])
            old_type_count = copy.copy(type_count)
            # print('initial, 999909909', old_type_count, type_count)

            for idx, i in enumerate(type_count):
                if i[0] == TD[c][0]:
                    type_count[idx][1] += 1
            type_count = np.array(type_count)
            type_count = type_count[np.argsort(type_count[:, 1])[::-1]]
            result += TD[c][1]
            # i個最大のものをとって、Kに達していたら終了
            if type_count[0][1] > K - k + 1:
                # print('111111', old_type_count)
                type_count = copy.copy(old_type_count)
                result -= TD[c][1]
                # print('result0', result)
                c += 1
                continue

            # ちょうどK個選んだ場合
            # print('選んだ個数合計', sum([i[1] for i in type_count[:k]]))
            if sum([i[1] for i in type_count[:k]]) == K:
                # 0がある場合はだめ
                if any([i[1] == 0 for i in type_count[:k]]):
                    # print('======', c, type_count)
                    result -= TD[c][1]
                    type_count = copy.copy(old_type_count)
                    # print('result1', result)
                    c += 1
                    continue
                # print('end type-count\n', type_count)
                return result
            if c == len(TD-1):
                return 0
            # print('type_count ending', type_count)
            # print('result2', result)
            old_type_count = copy.copy(type_count)
            c += 1


main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
sushi = []
for i in range(n):
    tmp = list(map(int, input().split()))
    sushi.append(tmp)
eaten = set() # 食べた種類を記憶(集合型)
chohuku = [] # 同じ種類で二回以上食べた寿司のスコアを記録
scores = [] # Sのスコアのリスト

sushi.sort(key=lambda x:x[1])
sushi.reverse() # sushiをおいしさの降順にソート

tmp = 0 # Sのおいしさの合計を保持
for i in range(k): # sushiを美味しい順にk個食べる
    if sushi[i][0] in eaten: # 同じ種類の寿司を食べていた場合
        chohuku.append(sushi[i][1])
    else:
        eaten.add(sushi[i][0]) # 食べた寿司の種類を記憶
    tmp += sushi[i][1] # 食べた寿司のおいしさをtmpに追加
chohuku.sort()
scores.append(tmp+len(eaten)**2) # 今のSのスコアを記憶

for i in range(k,n):
    if not sushi[i][0] in eaten and eaten != []:
        tmp -= chohuku.pop()
        eaten.add(sushi[i][0])
        tmp += sushi[i][1]
        scores.append(tmp+len(eaten)**2)
        
print(max(scores))