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:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, TD):
    TD.sort(key=lambda x: x[1], reverse=True)

    c = Counter()
    base = 0
    rc = []
    for i in range(K):
        t, k = TD[i]
        c[t] += 1
        base += k
        if c[t] > 1:
            rc.append((t, k))

    mi = i
    ans = base + len(c)**2
    while True:
        if len(rc) == 0:
            break
        rt, rk = rc.pop()
        for i in range(mi+1, len(TD)):
            if TD[i][0] not in c:
                c[TD[i][0]] += 1
                c[rt] -= 1
                base -= rk
                base += TD[i][1]
                mi = i
                ans = max(ans, base + len(c)**2)
                break
    return ans


def main():
    # N = read_int()
    N, K = read_int_n()
    TD = [read_int_n() for _ in range(N)]
    print(slv(N, K, TD))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools
import collections

x = input()
info = [int(i) for i in x.split()]
N = info[0]
K = info[1]
sushi = []
for i in range(N):
    input_line = input()
    sushi.append([int(x) for x in input_line.split()])

combination = itertools.combinations(sushi, K)

max = 0
for i in combination:
    satisfaction = 0
    temp = []
    for j in i:
        satisfaction += j[1]
        temp.append(j[0])
    bonus = (len(list(set(temp))))**2
    point = satisfaction + bonus
    if point>max:
        max = point
print(max)

Submission status: Time Limit Exceeded

Solution code:
N,K = (int(x) for x in input().split())
t_arr = [0]*(N+1)
d_arr = [0]*(N+1)
for i in range(N):
    t,d = tuple(int(x) for x in input().split())
    t_arr[i+1] = t
    d_arr[i+1] = d

td_index = list(range(1,N+1))
td_index.sort(key=lambda x:d_arr[x], reverse=True)

n_dm_set = set()
small_arr = []
d_dm = 0
for i in td_index[:K]:
    t = t_arr[i]
    d = d_arr[i]
    if t in n_dm_set:
        small_arr.append(d)
    n_dm_set.add(t)
    d_dm += d

current_max = len(n_dm_set)**2+d_dm

bucket = [0]*(N+1)
for t in n_dm_set:
    bucket[t] = -1

d_x = d_dm
nt_x = len(n_dm_set)
for i in td_index[K:]:
    t = t_arr[i]
    if bucket[t] != 0:
        continue
    d = d_arr[i]
    bucket[t] = d
    if len(small_arr) == 0:
        break
    d_x += d
    d_x -= small_arr[-1]
    small_arr = small_arr[:-1]
    nt_x += 1
    current_max = max(current_max, nt_x**2+d_x)

print(current_max)

Submission status: Time Limit Exceeded

Solution code:
N,K = (int(x) for x in input().split())
t_arr = [0]*(N+1)
d_arr = [0]*(N+1)
for i in range(N):
    t,d = tuple(int(x) for x in input().split())
    t_arr[i+1] = t
    d_arr[i+1] = d

td_index = list(range(1,N+1))
td_index.sort(key=lambda x:d_arr[x], reverse=True)

n_dm_set = set()
small_arr = []
d_dm = 0
for i in td_index[:K]:
    t = t_arr[i]
    d = d_arr[i]
    if t in n_dm_set:
        small_arr.append(d)
    n_dm_set.add(t)
    d_dm += d

candidate_dict = {}
candidate_dict[len(n_dm_set)] = d_dm

bucket = [0]*(N+1)
for t in n_dm_set:
    bucket[t] = -1

d_x = d_dm
nt_x = len(n_dm_set)
for i in td_index[K:]:
    t = t_arr[i]
    if bucket[t] != 0:
        continue
    d = d_arr[i]
    bucket[t] = d
    if len(small_arr) == 0:
        break
    d_x += d
    d_x -= small_arr[-1]
    small_arr = small_arr[:-1]
    nt_x += 1
    candidate_dict[nt_x] = d_x

ans = 0
for k,v in candidate_dict.items():
    ans = max(ans, k*k+v)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = (int(x) for x in input().split())
td_arr = []
for _ in range(N):
    td = tuple(int(x) for x in input().split())
    td_arr.append(td)

td_arr.sort(key=lambda x:x[1], reverse=True)

n_dm_set = set()
small_arr = []
d_dm = 0
for t,d in td_arr[:K]:
    if t in n_dm_set:
        small_arr.append(d)
    n_dm_set.add(t)
    d_dm += d

candidate_dict = {}
candidate_dict[len(n_dm_set)] = d_dm

prev_t = -1
other_arr = []
for t,d in sorted(td_arr, key=lambda x:x[0]):
    if t == prev_t:
        continue
    if t in n_dm_set:
        continue
    prev_t = t
    other_arr.append((t,d))
other_arr.sort(key=lambda x:x[1], reverse=True)

d_x = d_dm
nt_x = len(n_dm_set)
for t,d in other_arr:
    if len(small_arr) == 0:
        break
    d_x += d
    d_x -= small_arr[-1]
    small_arr = small_arr[:-1]
    nt_x += 1
    candidate_dict[nt_x] = d_x

ans = 0
for k,v in candidate_dict.items():
    ans = max(ans, k*k+v)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = (int(x) for x in input().split())
td_arr = []
for _ in range(N):
    td = tuple(int(x) for x in input().split())
    td_arr.append(td)

td_arr.sort(key=lambda x:x[1], reverse=True)

n_dm_set = set()
small_arr = []
d_dm = 0
for t,d in td_arr[:K]:
    if t in n_dm_set:
        small_arr.append(d)
    n_dm_set.add(t)
    d_dm += d

candidate_dict = {}
candidate_dict[len(n_dm_set)] = d_dm

n_x_set = set(n_dm_set)
d_x = d_dm
for t,d in td_arr[K:]:
    if t in n_x_set:
        continue
    if len(small_arr) == 0:
        break
    n_x_set.add(t)
    d_x += d
    d_x -= small_arr[-1]
    small_arr = small_arr[:-1]
    candidate_dict[len(n_x_set)] = d_x

ans = 0
for k,v in candidate_dict.items():
    ans = max(ans, k*k+v)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter

n, k = map(int, input().split())
td = [tuple(int(x) for x in input().split()) for _ in range(n)]

a = sorted(td, key=itemgetter(1), reverse=True)

ans = [0]
s = []
t = []
for i in range(k):
    ans[0] += a[i][1]
    if a[i][0] not in s:
        s.append(a[i][0])
    else:
        t.append(a[i][1])

p = len(s)
q = len(t) - 1

if q < 0:
    print(ans[0] + k * k)
    exit()

v = []
for i in range(k, n):
    if a[i][0] not in s:
        s.append(a[i][0])
        v.append(a[i][1])

ans[0] += p * p
d = 0

for x in v:
    ans.append(ans[d] + x - t[q] + (p + 1) * (p + 1) - p * p)
    p += 1
    d += 1
    q -= 1
    if q < 0:
        break

print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter

n, k = map(int, input().split())
td = [tuple(int(x) for x in input().split()) for _ in range(n)]

a = sorted(td, key=itemgetter(1), reverse=True)

ans = [0]
v = []
s = []
for i in range(k):
    ans[0] += a[i][1]
    if a[i][0] not in s:
        s.append(a[i][0])
        v.append([a[i][1]])
    else:
        v[s.index(a[i][0])].append(a[i][1])
ans[0] += (len(s)) ** 2

t = []
d = []
for x, y in a[k:]:
    if x in s:
        continue
    elif x not in t:
        t.append(x)
        d.append([y])
    else:
        d[t.index(x)].append(y)

td = []
for i in range(len(t)):
    td.append((t[i], max(d[i])))

td = sorted(td, key=itemgetter(1), reverse=True)

ms = len(s)
p = 0
g = ms

for i in range(ms):
    v[i] = sorted(v[i])

#print(v)

for x, y in td:
    min_s = -1
    min_v = a[0][1]
    for i in range(ms):
        if len(v[i]) > 1:
            if min_v > v[i][0]:
                min_s = i
                min_v = v[i][0]
    if min_s == -1:
        break
    ans.append(ans[p] - min_v + y - g * g + (g + 1) * (g + 1))
    v[min_s].remove(v[min_s][0])
    g += 1
    p += 1

print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
import itertools
N,K=map(int,input().split(" "))
T_D=[]
for _ in range(N):
    t,d=map(int,input().split(" "))
    T_D.append([t,d])
T_D=list(itertools.combinations(T_D,K))
tmax=-1
for tp in T_D:
    p=0
    v=set()
    for e in tp:
        v.add(e[0])
        p+=e[1]
    p+=len(v)*len(v)
    tmax=max(tmax,p)
print(tmax)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import heapq
n ,k = map(int, input().split())

used = []
unused = []
for i in range(n):
    t, d = map(int, input().split())
    unused.append((-d,t))
heapq.heapify(unused)
# 最初の集合
c = Counter()
ans = []
kiso = 0
for i in range(k):
    d, t = heapq.heappop(unused)
    kiso -= d
    c[t] += 1
    heapq.heappush(used,(-d, t))
bonus = len(c)
ans.append(kiso + bonus**2)

for i in range(k):
    # いらないものを抜く
    flag = False
    atode = []
    while used:
        d, t = heapq.heappop(used)
        if c[t] > 1:
            c[t] -= 1
            kiso -= d
            flag = True
            break
        atode.append((d,t))
    for i in atode:
        heapq.heappush(used, i)
    # 全部の種類が1つしかない場合
    if not flag:break
    # 種類を増やす
    flag = False
    atode = []
    while unused:
        d, t = heapq.heappop(unused)
        if c[t]==0:
            bonus+=1
            kiso += -d
            c[t] += 1
            heapq.heappush(used, (-d, t))
            flag = True
            break
        atode.append((d,t))
    for i in atode:
        heapq.heappush(unused, i)
    # 種類を増やせなかった場合
    if not flag:break
    ans.append(kiso + bonus**2)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
N, K = [int(x) for x in input().split()]
orig_td = [tuple([int(x) for x in input().split()]) for _ in range(N)]
td = sorted(orig_td.copy(), key=lambda x: x[1], reverse=True)
INF = 10**9
# print(td)


def score(a):
    kiso = sum([x[1] for x in a])
    bonus = len(set([x[0] for x in a]))**2
    return kiso + bonus


first = []
second = []
kind = set()
for i in range(K):
    if td[i][0] not in kind:
        first.append(td[i])
        kind.add(td[i][0])
    else:
        second.append(td[i])

best_ans = sum([x[1] for x in first + second]) + len(first)**2

for k in range(K, N):
    if len(second) == 0:
        break
    if td[k][0] in kind:
        continue

    a = second.pop(-1)
    kind.add(td[k][0])
    first.append(td[k])
    ans = sum([x[1] for x in first + second]) + len(first)**2
    # print(first, second, ans)
    if best_ans < ans:
        best_ans = ans
print(best_ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, K = [int(x) for x in input().split()]
orig_td = [tuple([int(x) for x in input().split()]) for _ in range(N)]
td = orig_td.copy()
INF = 10**9
# print(td)


def score(a):
    kiso = sum([x[1] for x in a])
    # print(a)
    bonus = len(set([x[0] for x in a]))**2
    return kiso + bonus


total = score(td)
for i in range(N, K, -1):
    # print("i", i)
    max_score = -INF
    useless_neta = 0
    for neta in td:
        te = td.copy()
        te.remove(neta)
        kari = score(te)
        if kari > max_score:
            max_score = kari
            useless_neta = neta
    td.remove(useless_neta)
    # print(td)
print(score(td))

# print("全列挙", max([score(x) for x in itertools.permutations(orig_td, K)]))

Submission status: Time Limit Exceeded

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

T = 0
neta = []
doublecounts = []
ans = []

for i in range(K):
    T += TD[i][1]    
    if not(TD[i][0] in neta):    
        neta.append(TD[i][0])    
    else:      
        doublecounts.append(TD[i][1])    
            
ans.append(T+len(neta)**2)

for i in range(K,N):
    if(len(doublecounts)==0):
        break
    if not(TD[i][0] in neta):
        T -= doublecounts.pop(-1)
        T += TD[i][1]
        neta.append(TD[i][0])
        ans.append(T+len(neta)**2)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())



def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))
#-----------------------------------------

li.sort(reverse=True,key=lambda x:x[1])
s2=min(find_num_neta(list(range(n)),li),k)
s1=find_num_neta(list(range(k)),li)

#-----------------------------------------
li.sort(key=lambda x:x[0])
best_list=[]
not_best_list=[]


m=-1
for i in li:
    if m==i[0]:
        not_best_list.append(i)
    else:
        best_list.append(i)
        m=i[0]
        
not_best_list.sort(reverse=True,key=lambda x:x[1])
best_list.sort(reverse=True,key=lambda x:x[1])



 
 
score=-1
for i in range(s1,s2+1):
    oishisa=0
    for j in range(i):
        oishisa+=best_list[j][1]
    for j in range(k-i):
        oishisa+=not_best_list[j][1]
    
    new_score=i**2+oishisa
    
    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())
 
li.sort(reverse=True,key=lambda x:x[1])
 
def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))
 
#-----------------------------------------
best_list=[]
best_list_neta=[]
not_best_list=[]
 
for i in li:
    if i[0] in best_list_neta:
        not_best_list.append(i[1])
    else:
        best_list.append(i[1])
        best_list_neta.append(i[0])
 
 
s2=min(len(best_list_neta),k)
s1=find_num_neta(list(range(k)),li)
 
 
score=-1
for i in range(s1,s2+1):
    oishisa=0
    for j in range(i):
        oishisa+=best_list[j]
    for j in range(k-i):
        oishisa+=not_best_list[j]
    
    new_score=i**2+oishisa
 
    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())

li.sort(reverse=True,key=lambda x:x[1])

def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))

#-----------------------------------------
best_list=[]
best_list_neta=[]
not_best_list=[]

for i in li:
    if i[0] in best_list_neta:
        not_best_list.append(i)
    else:
        best_list.append(i)
        best_list_neta.append(i[0])


s2=min(find_num_neta(list(range(n)),li),k)
s1=find_num_neta(list(range(k)),li)


score=-1
for i in range(s1,s2+1):
    oishisa=0
    for j in range(i):
        oishisa+=best_list[j][1]
    for j in range(k-i):
        oishisa+=not_best_list[j][1]
    
    new_score=i**2+oishisa

    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())

#####################
li.sort(reverse=True,key=lambda x:x[1])

def calc_score(li,choice):
    score=0
    k=[]
    for i in choice:
        score+=li[i][1]
        k.append(li[i][0])        
    score+=len(set(k))**2
    return score

def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))

#-----------------------------------------
best_list=[]
not_best_list=[]

for i in li:
    if i[0] in [best_list[p][0] for p in range(len(best_list))]:
        not_best_list.append(i)
    else:
        best_list.append(i)

#-----------------------------------------


first_choice=list(range(k))
score=calc_score(li,first_choice)
li_choice_set=set([li[i][0] for i in first_choice])


#------------------------------------------------
s2=min(find_num_neta(list(range(n)),li),k)
s1=find_num_neta(first_choice,li)


for i in range(s1+1,s2+1):

    oishisa=0
    for j in range(i):
        oishisa+=best_list[j][1]
    for j in range(k-i):
        oishisa+=not_best_list[j][1]
    
    new_score=i**2+oishisa

    
    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())

li.sort(reverse=True,key=lambda x:x[1])

def calc_score(li,choice):
    score=0
    k=[]
    for i in choice:
        score+=li[i][1]
        k.append(li[i][0])        
    score+=len(set(k))**2
    return score

def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))

#-----------------------------------------
best_list=[]
not_best_list=[]

for i in li:
    if i[0] in [best_list[p][0] for p in range(len(best_list))]:
        not_best_list.append(i)
    else:
        best_list.append(i)
    
        


#-----------------------------------------


first_choice=list(range(k))
score=calc_score(li,first_choice)
li_choice_set=set([li[i][0] for i in first_choice])


#------------------------------------------------
s2=min(find_num_neta(list(range(n)),li),k)
s1=find_num_neta(first_choice,li)


for i in range(s1+1,s2+1):
    new_choice=first_choice.copy()
    change=i-s1
    can_append=change
    must_delete=change
    

    
    
    for j in range(k,n):

        if li[j][0] not in [li[i][0] for i in new_choice]:
            
            new_choice.append(j)
            can_append+=-1
            if can_append==0:
                break
            
            
    for j in range(k-1,-1,-1):

        if li[j][0] in [li[p][0] for p in range(j)]:
            new_choice.remove(j)
            must_delete+=-1
            if must_delete==0:
                break
        
    
    new_score=calc_score(li,new_choice)

    
    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())
 

li.sort(reverse=True,key=lambda x:x[1])

def calc_score(li,choice):
    score=0
    k=[]
    for i in choice:
        score+=li[i][1]
        k.append(li[i][0])        
    score+=len(set(k))**2
    return score

def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))

#-----------------------------------------
best_list=[]
not_best_list=li.copy()

for i in li:
    if i[0] not in [best_list[p][0] for p in range(len(best_list))]:
        best_list.append(i)

for i in best_list:
    not_best_list.remove(i)

#-----------------------------------------


first_choice=list(range(k))
score=calc_score(li,first_choice)
li_choice_set=set([li[i][0] for i in first_choice])


#------------------------------------------------
s2=min(find_num_neta(list(range(n)),li),k)
s1=find_num_neta(first_choice,li)


for i in range(s1+1,s2+1):

    oishisa=0
    for j in range(i):
        oishisa+=best_list[j][1]
    for j in range(k-i):
        oishisa+=not_best_list[j][1]
    
    new_score=i**2+oishisa

    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
li=[[0,0] for i in range(n)]
for i in range(n):
    li[i][0],li[i][1]=map(int,input().split())
 
 
li.sort(reverse=True,key=lambda x:x[1])
 

def calc_score(li,choice):
    score=0
    k=[]
    for i in choice:
        score+=li[i][1]
        k.append(li[i][0])        
    score+=len(set(k))**2
    return score

def find_num_neta(choice,li):
    k=[]
    for i in choice:
        k.append(li[i][0])
    return len(set(k))

first_choice=list(range(k))
score=calc_score(li,first_choice)

li_choice_set=set([li[i][0] for i in first_choice])


s2=min(find_num_neta(list(range(n)),li),k)
s1=find_num_neta(first_choice,li)

for i in range(s1+1,s2+1):
  
    new_choice=first_choice.copy()
    change=i-s1
    can_append=change
    must_delete=change
    

    
    
    for j in range(k,n):
     #   print(set([li[i][0] for i in new_choice]),i,li[j][0])
        if li[j][0] not in [li[i][0] for i in new_choice]:
            
            new_choice.append(j)
            can_append+=-1
            if can_append==0:
                break
            
            
    for j in range(k-1,-1,-1):

        if li[j][0] in [li[p][0] for p in range(j)]:
            new_choice.remove(j)
            must_delete+=-1
            if must_delete==0:
                break
        
    
    new_score=calc_score(li,new_choice)

    
    if score<new_score:
        score=new_score
        
    
print(score)

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, K = map(int, input().split())
    sushis = [[] for _ in range(N)]
    for i in range(N):
        t, d = map(int, input().split())
        sushis[t-1].append(d)
    for i in range(N):
        sushis[i].sort(reverse=True)
        cumsum = 0
        for j in range(len(sushis[i])):
            cumsum += sushis[i][j]
            sushis[i][j] = cumsum
    dp = [[None] * (K+1) for _ in range(2)]
    dp[1][0] = (0, 0)
    dp[0][0] = (0, 0)
    for i in range(N):
        dp[i % 2] = [x for x in dp[(i-1) % 2]]
        for j in range(len(sushis[i])):
            for k in range(K-j):
                if dp[(i-1) % 2][k] is None:
                    continue
                pt, pd = dp[(i-1) % 2][k]
                if dp[i % 2][k+j+1] is None or pd + sushis[i][j] + 2 * pt + 1 >= dp[i % 2][k+j+1][1]:
                    dp[i % 2][k+j+1] = (pt+1, pd + sushis[i][j] + 2 * pt + 1)
    print(dp[(N-1) % 2][K][1])


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
#  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)
            result = max(type_bonus**2 + base_point, result)

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


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
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)
            result = max(type_bonus**2 + base_point, result)

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


if __name__ == '__main__':
    main()