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: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def __str__(self):
        return  str(self.edges)
 
    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)

show_flg=False
show_flg=True
ans=0


n,k=LI()
s=[]
for _ in range(n):
    t,d=LI()
    s+=[(d,t)]


s.sort(key=lambda x:x[0])
org_s=s[:]

q=[]
init_q=[[]for i in range(n+1)]
ate=[0]*-~n
cnt=[0]*-~n
for i in range(k):
    d,t=s.pop()
    ate[t]=1
    cnt[t]+=1
    ans+=d
    heappush(init_q[t],(d,t))
for i in range(n):
    while init_q[i] and len(init_q[i])>1:
        d,t=heappop(init_q[i])
        heappush(q,(d,t))
x=sum(ate)
ans+=x*x

while s and q:
    tmp=ans
    d,t=s.pop()
    if ate[t]==1:
        continue
    rd,rt=heappop(q)
    if cnt[rt]==1:
        rd,rt=heappush(q,(rd,rt))
        continue
    tmp-=rd
    tmp+=d
    tmp+=2*x+1
    
    
    ans=tmp
    #heappush(q,(d,t))
    ate[t]=1
    cnt[rt]-=1
    x+=1


    #show(q,ate,(d,t),(rd,rt),tmp)


print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import *

N, K = map(int, input().split())
td = [tuple(map(int, input().split())) for _ in range(N)]
td.sort(key=lambda t: t[1], reverse=True)
d = defaultdict(list)
now = 0

for ti, di in td[:K]:
    d[ti].append(di)
    now += di

rem = []

for k in d.keys():
    d[k].sort(reverse=True)
    
    for i in range(1, len(d[k])):
        rem.append(d[k][i])

add = []
s = set()

for ti, di in td[K:]:
    if ti not in d and ti not in s:
        add.append(di)
        s.add(di)

rem.sort()
add.sort(reverse=True)
var = len(list(d.keys()))
ans = now+var**2

for i in range(min(len(rem), len(add))):
    now -= rem[i]
    now += add[i]
    ans = max(ans, now+(var+i+1)**2)

print(ans)

Submission status: Wrong Answer

Solution code:

n, k = list(map(int, input().split()))
sushi = []
for i in range(n):
    sushi.append(list(map(int, input().split())))
point = 0
sushi_kind = set()
duplication = []
sushi.sort(key=lambda x: x[1],reverse = True)
for i in range(k):
    point += sushi[i][1]
    if sushi[i][0] in sushi_kind:
        duplication.append(sushi[i])
    else:
        sushi_kind.add(sushi[i][0])
ans = point + pow(len(sushi_kind),2)
dup_index = len(duplication) - 1
for i in range(k,n):
    if sushi[i][0] in sushi_kind:
        continue
    else:
        point += sushi[i][1]
        sushi_kind.add(sushi[i][0])
        if dup_index >= 0:
            point -= duplication[dup_index][1]
            dup_index -= 1
    ans = max(ans, point + pow(len(sushi_kind),2))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from heapq import heappop, heappush

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

TD.sort(key = lambda x: -x[1])
#print(TD)

answer = 0

cnt = [[] for _ in range(N + 1)]
for i in range(K):
    t, d = TD[i]
    answer += d
    cnt[t].append(d)
#print(cnt)

kind = 0
candidate_out = []
for i in range(N + 1):
    if cnt[i]:
        cnt[i].sort(reverse = True)
        if len(cnt[i]) >= 2:
            for j in range(1, len(cnt[i])):
                candidate_out.append(cnt[i][j])
        kind += 1
answer += kind ** 2
answer_lst = []
answer_lst.append(answer)

#print(answer)
#print(candidate_out)

candidate_in = []
if N > K:
    for i in range(K, N):
        candidate_in.append(TD[i])
candidate_in.sort(key = lambda x: -x[1])
#print(candidate_in)

candidate_out.sort(reverse = True)

while candidate_in and candidate_out:
    t, ci = candidate_in.pop()
    if cnt[t]:
        continue
    else:
        co = candidate_out.pop()
        answer -= kind ** 2
        answer -= co
        kind += 1
        answer += kind ** 2
        answer += ci
        answer_lst.append(answer)
        
print(max(answer_lst))

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import defaultdict

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

DT = [[d, t] for t, d  in TD]
DT.sort(reverse = True)
#print(DT)

h_in = []
cnt = defaultdict(int)

tmp = []
kiso = 0
for d, t in DT:
    if cnt[t] == 0:
        heappush(h_in, [d, t])
        kiso += d
    else:
        tmp.append([d, t])
    cnt[t] += 1

tmp = tmp[::-1]
len_h_in = len(h_in)
if len_h_in < K:
    d = K - len_h_in
    for i in range(d):
        heappush(h_in, tmp[i])
        kiso += tmp[i][0]

kind = 0
for k, v in list(cnt.items()):
    if v:
        kind += 1
#print(kiso, kind)
#print(h_in)
#print(tmp)

answer = kiso + kind ** 2
tmp = tmp[::-1]
while tmp:
    out_d, out_t = tmp.pop()
    in_d, in_t = heappop(h_in)
    
    kiso += out_d - in_d
    cnt[in_t] -= 1
    if cnt[in_t] == 0: kind -= 1
    cnt[out_t] += 1
    if cnt[out_t] == 1: kind += 1
    
    heappush(h_in, [out_d, out_t])
    
    answer = max(answer, kiso + kind ** 2)

print(answer)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#%% for atcoder uniittest use
import sys
input= lambda: sys.stdin.readline().rstrip()
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
#%%code

def resolve():
    N,K=pin()
    neta=[]
    for i in range(N):
        x,y=pin()
        neta.append([x,y,0])
    neta.sort(key=lambda x:x[1])
    #print(neta)

    start_point=0
    netaset=set()
    for i in range(K):
        x,y,z=neta[N-i-1]
        netaset.add(x)
        start_point+=y
    start_point+=len(netaset)**2
    #print(start_point)


    neta.sort(key=lambda x:x[0])
    #print(neta)
    netaset=set()
    t=0
    neopoint=0
    neta2=neta[:]
    for i in range(0,N-1):
        if neta2[i+1][0]!=neta2[i][0]:
            t+=1
            s,f,q=neta[i]
            netaset.add(s)
            neopoint+=f
            neta[i][2]=1
    #print(neta)
    s,f,q=neta[N-1]
    netaset.add(s)
    neopoint+=f
    neta[i][2]=1
    
    #print(neopoint)
    a=K-t-1
    neta.sort(key=lambda x:x[1])
    #print(a,neta)
    if a>0:
        while(a>0):
            pp,qq,rr=neta.pop()
            if rr==0:
                a-=1
                netaset.add(pp)
                neopoint+=qq
    neopoint+=len(netaset)**2
    #print(max(neopoint,start_point))
    
        
            
    print(max(start_point,neopoint))
#%%submit!
resolve()

Submission status: Wrong Answer

Solution code:
# D - Various Sushi
import sys
from collections import defaultdict
import heapq
readline = sys.stdin.readline

dd = defaultdict(list)
N, K = map(int, readline().split())
for i in range(N):
    t, d = map(int, readline().split())
    heapq.heappush(dd[t], d*-1)

dd = list(dd.values())
dd.sort()

ans = 0
tmp_max = 0
fix = 0
var = []
for i in range(len(dd)):
    fix += heapq.heappop(dd[i]) * -1
    for _ in range(K-(i+1)):
        if len(dd[i]) > 0:
            tmp = heapq.heappop(dd[i]) * -1
            tmp_max = max(tmp, tmp_max)
            if tmp <= tmp_max and len(var) > K-(i+1):
                break
            heapq.heappush(var, tmp)
    while len(var) > K-(i+1) and len(var) > 0:
        heapq.heappop(var)
    if len(var) == K-(i+1):
        ans = max(ans , fix+sum(var) + (i+1)**2)

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).


def main():
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def mi():    return map(int, input().split())
    def lmi():   return list(map(int, input().split()))
    

    class MaxPQueue:
        def __init__(self):
            self.h = []
            self.size = 0

        def is_empty(self):
            return self.size == 0
        
        def push(self, delicious_dq):
            self.size += 1
            heappush(self.h, list(map(lambda x: -x, delicious_dq)))
        
        def pop(self):
            self.size -= 1
            tmp = heappop(self.h)
            return list(map(lambda x: -x, tmp)) 


    n, k = mi()
    L = [lmi() for _ in range(n)]
    L.sort(key=lambda x: x[1], reverse=True)

    d = dict()
    for neta, delcious in L:
        if neta in d:
            d[neta].append(delcious)
        else:
            d[neta] = [delcious]

    group_num = dict()
    group_size = 0
    ans = 0
    for neta, delcious in L[:k]:
        ans += delcious
        if neta in group_num:
            group_num[neta] += 1
        else:
            group_num[neta] = 1
            group_size += 1
    ans += group_size ** 2
    
    pq_new = MaxPQueue()
    for neta in d.keys():
        if neta not in group_num:
            pq_new.push(d[neta])
    
    # print(L)
    # print(ans)
    # print(group_num)
    prev = ans
    for ind in range(k-1, -1, -1):
        neta, delicious = L[ind]
        if group_num[neta] > 1 and not pq_new.is_empty():
            diff = pq_new.pop()[-1] + (2 * group_size + 1) - delicious
            ans = max(ans, prev + diff)
            prev += diff
            group_size += 1
            group_num[neta] -= 1
            # print(f"prev {prev}")            
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    class MaxPQueue:
        def __init__(self):
            self.h = []
            self.size = 0
        
        def is_empty(self):
            return self.size == 0
        
        def push(self, delicious_dq):
            tmp = deque(map(lambda x: -x, delicious_dq))
            heappush(self.h, tmp)
            self.size += 1
        
        def pop(self):
            minus_delicious_dq = heappop(self.h)
            self.size -= 1
            return deque(map(lambda x: -x, minus_delicious_dq))
    

    n, k = mi()
    d = defaultdict(list)
    for _ in range(n):
        neta, delicious = mi()
        d[neta].append(delicious)
    
    pq_chosen_group = MaxPQueue()
    pq_new_group = MaxPQueue()

    for neta in d.keys():
        d[neta].sort(reverse=True)
        pq_new_group.push(deque(d[neta]))
    

    variety_size = 0
    point = 0

    for _ in range(k):
        # print(f"point {point}")
        if pq_new_group.is_empty():
            # print('a')
            delicious_dq_chosen = pq_chosen_group.pop()
            point += delicious_dq_chosen.popleft()
            if delicious_dq_chosen:
                pq_chosen_group.push(delicious_dq_chosen)
        
        elif pq_chosen_group.is_empty():
            # print('b')
            delicious_dq_new = pq_new_group.pop()
            variety_size += 1
            point += delicious_dq_new.popleft()
            point += variety_size ** 2 - (variety_size - 1) ** 2
            if delicious_dq_new:
                pq_chosen_group.push(delicious_dq_new)
        
        else:
            delicious_dq_chosen = pq_chosen_group.pop()
            delicious_dq_new = pq_new_group.pop()
            if delicious_dq_chosen[0] > delicious_dq_new[0] + ((variety_size + 1) ** 2 - (variety_size ** 2)):
                # print('c')
                pq_new_group.push(delicious_dq_new)    # push back
                point += delicious_dq_chosen.popleft()
                if delicious_dq_chosen:
                    pq_chosen_group.push(delicious_dq_chosen)
            else:
                # print('d')
                pq_chosen_group.push(delicious_dq_chosen)    # push back
                variety_size += 1
                point += delicious_dq_new.popleft()
                point += variety_size ** 2 - (variety_size - 1) ** 2
                if delicious_dq_new:
                    pq_chosen_group.push(delicious_dq_new)
    # print(variety_size)
    print(point)  
                       




if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
nums = []
for i in range(N):
    t, d = map(int, input().split())
    nums.append((d, t))
nums.sort(reverse=True)
se = set()
a1 = []
a2 = []
rest = []
for i, n in enumerate(nums):
    if i < K:
        if not n[1] in se:
            se.add(n[1])
            a1.append(n)
        else:
            a2.append(n)
    else:
        rest.append(n)
points = 0
for (d, t) in a1: points += d
for (d, t) in a2: points += d
ans = points + pow(len(se), 2)
a2.sort()
for i, (d, t) in enumerate(rest):
    if t in se: continue
    if i >= len(a2): break
    points -= a2[i][0]
    points += d
    se.add(t)
    ans = max(ans, points+pow(len(se), 2))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
nums = []
for i in range(N):
    t, d = map(int, input().split())
    nums.append((d, t))
nums.sort(reverse=True)
se = set()
kind = 0
a1 = []
a2 = []
rest = []
for i, n in enumerate(nums):
    if i < K:
        if not n[1] in se:
            se.add(n[1])
            kind += 1
            a1.append(n)
        else:
            a2.append(n)
    else:
        rest.append(n)
points = 0
for (d, t) in a1: points += d
for (d, t) in a2: points += d
ans = points + pow(kind, 2)
a2.sort()
for i, (d, t) in enumerate(rest):
    if t in se: continue
    if i >= len(a2): break
    points -= a2[i][0]
    points += d
    kind += 1
    ans = max(ans, points+pow(kind, 2))
print(ans)

Submission status: Wrong Answer

Solution code:
N,K,*L = map(int, open(0).read().split())
ls = []
for i,(t,d) in enumerate(zip(*[iter(L)]*2)):
  ls.append((d,t))
ls.sort()
S = set()
pre = []
ans = 0
num = 0
for i in range(K):
  d,t = ls.pop()
  ans += d
  if t not in S:
    S.add(t)
  else:
    pre.append(d)
pre.sort(reverse=True)
ans += num*num
if pre==[]:
  print(ans)
  exit()
m = ans
for i in range(N-K):
  d,t = ls.pop()
  if t in S:
    continue
  S.add(t)
  m -=pre.pop()
  m += d+2*num+1
  num += 1
  ans = max(ans,m)
  if pre==[]:
    break
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
N,K,*L = map(int, open(0).read().split())
dic = defaultdict(list)
for t,d in zip(*[iter(L)]*2):
  dic[t].append(d)
for k in dic.keys():
  dic[k].sort(reverse=True)
ls = sorted(dic.keys(), key=lambda x:dic[x][0],reverse=True)
eat = []
num = 0
ans = 0
k = ls[0]
i = 0
while len(eat)+num<K:
  num += 1
  ans += dic[k][0]
  if K-len(eat)-num<=len(dic[k])-1:
    eat += dic[k][1:K-len(eat)-num+1]
  else:
    eat += dic[k][1:]
    i += 1
    k = ls[i]
ans += sum(eat) + num*num
eat.sort()
m = ans
j = 0
while num<K:
  i += 1
  if i==len(ls):
    break
  k = ls[i]
  m -= eat[j]
  j += 1
  m += dic[k][0]+2*num+1
  num += 1
  ans = max(ans,m)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

n,k = map(int,input().split())
td = {}
dt = [() for _ in range(n)]
for i in range(n):
    t,d = map(int,input().split())
    dt[i] = (d,t)
dt.sort(reverse = True)
cnt = 0
parent = []
used = set()
child = []
for d,t in dt:
    if t not in used:
        used.add(t)
        cnt += d
        parent.append(d)
    else:
        child.append(d)
p = len(parent)
c = len(child)
ans = cnt
ans += p**2
last = p-1
will = 0
for i,c in enumerate(child):
    if not(0<=will<c and 0<=last<p):break
    if i+p+1 > k:
        cnt += child[will] - parent[last]
        will += 1
        last -= 1
        p -= 1
    elif i+p+1 < k:
        cnt += child[will]
        will += 1
    ans = max(ans, cnt + p**2)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n,k=map(int,input().split())
td=[[0]*2 for _ in range(n)]
for i in range(n):
    t,d=map(int,input().split())
    td[i][0],td[i][1]=d,t
td.sort(reverse=True)
di=set()
sa=deque()
ans=0
for d,t in td[:k]:
    if t in di:
        sa.append(d)
    else:
        di.add(t)
    ans+=d

s=[-10**18]*(k+1)
cnt=len(di)
s[cnt]=ans
for d,t in td[k:]:
    if t in di:
        continue
    else:
        if sa:
            x=sa.popleft()
            ans+=d-x
            di.add(t)
            cnt+=1
            s[cnt]=ans

for i in range(k+1):
    s[i]+=i*i

print(max(s))

Submission status: Wrong Answer

Solution code:
import heapq
n,k=map(int,input().split())
td=[[0]*2 for _ in range(n)]
for i in range(n):
    t,d=map(int,input().split())
    td[i][0],td[i][1]=d,t
td.sort(reverse=True)
di=set()
sa=[]
heapq.heapify(sa)
ans=0
for d,t in td[:k]:
    if t in di:
        heapq.heappush(sa, d)
    else:
        di.add(t)
    ans+=d

s=[0]*(k+1)
cnt=len(di)
s[cnt]=ans
for d,t in td[k:]:
    if t in di:
        continue
    else:
        if sa:
            x=heapq.heappop(sa)
            ans+=d-x
            di.add(t)
            cnt+=1
            s[cnt]=ans

for i in range(k+1):
    s[i]+=i*i

print(max(s))

Submission status: Wrong Answer

Solution code:
from collections import deque
n,k=map(int,input().split())
td=[[0]*2 for _ in range(n)]
for i in range(n):
    t,d=map(int,input().split())
    td[i][0],td[i][1]=d,t
td.sort(reverse=True)
di=set()
sa=deque()
ans=0
for d,t in td[:k]:
    if t in di:
        sa.append(d)
    else:
        di.add(t)
    ans+=d

s=[0]*(k+1)
cnt=len(di)
s[cnt]=ans
for d,t in td[k:]:
    if t in di:
        continue
    else:
        if sa:
            x=sa.popleft()
            ans+=d-x
            di.add(t)
            cnt+=1
            s[cnt]=ans

for i in range(k+1):
    s[i]+=i*i

print(max(s))

Submission status: Wrong Answer

Solution code:
import heapq
n,k=map(int,input().split())
kind=[0]*n
s=set()
dt=[]
ans=0
for _ in range(n):
    t,d=map(int,input().split())
    ans+=d
    t-=1
    dt.append((d,t))
    s.add(t)
    kind[t]+=1
x=len(s)
ans+=x**2
sing,comp=[],[]
for d,t in dt:
    if kind[t]==1:
        heapq.heappush(sing,(d,t))
    elif kind[t]>=2:
        heapq.heappush(comp,(d,t))
infi=10**18
for _ in range(n-k):
    if sing:
        ds,ts=heapq.heappop(sing)
    else:
        ds,ts=infi,-1
    if comp:
        dc,tc=heapq.heappop(comp)
    else:
        dc,tc=infi,-1
    if ds+x**2-(x-1)**2>=dc:
        ans-=dc
        kind[tc]-=1
        if kind[tc]>=2:
            heapq.heappush(comp,(dc,tc))
        else:
            heapq.heappush(sing,(dc,tc))
        heapq.heappush(sing,(ds,ts))
    else:
        ans-=ds+x**2-(x-1)**2
        x-=1
        kind[ts]-=1
        heapq.heappush(comp,(dc,tc))
print(ans)

Submission status: Wrong Answer

Solution code:
import heapq
n,k=map(int,input().split())
kind=[0]*n
s=set()
dt=[]
ans=0
for _ in range(n):
    t,d=map(int,input().split())
    ans+=d
    t-=1
    dt.append((d,t))
    s.add(t)
    kind[t]+=1
x=len(s)
ans+=x**2
sing,comp=[],[]
for d,t in dt:
    if kind[t]==1:
        heapq.heappush(sing,(d,t))
    elif kind[t]>=2:
        heapq.heappush(comp,(d,t))
infi=10**18
for _ in range(n-k):
    if sing:
        ds,ts=heapq.heappop(sing)
    else:
        ds,ts=infi,-1
    if comp:
        dc,tc=heapq.heappop(comp)
    else:
        dc,tc=infi,-1
    if ds+x**2-(x-1)**2>dc:
        ans-=dc
        kind[tc]-=1
        if kind[tc]>=2:
            heapq.heappush(comp,(dc,tc))
        else:
            heapq.heappush(sing,(dc,tc))
        heapq.heappush(sing,(ds,ts))
    else:
        ans-=ds+x**2-(x-1)**2
        x-=1
        kind[ts]-=1
        heapq.heappush(comp,(dc,tc))
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    sushi = [list(map(int, input().split())) for _ in range(n)]
    sushi.sort(key=lambda x: x[1], reverse=True)
    ans = 0
    t = [0]*(n+1)
    tmp = 0
    cnt = 0
    for i in range(k):
        ans += sushi[i][1]
        if t[sushi[i][0]] == 0:
            cnt += 1
        tmp += sushi[i][1]
        t[sushi[i][0]] += 1
    ans = tmp + cnt*cnt
    p = k
    for i in range(k, n):
        f = False
        if t[sushi[i][0]] == 0:
            f = True
            for j in reversed(range(p)):
                if 1 < t[sushi[j][0]]:
                    t[sushi[j][0]] -= 1
                    tmp -= sushi[j][1]
                    tmp += sushi[i][1]
                    p = j
                    cnt += 1
                    ans = max(ans, tmp+cnt*cnt)
                    f = False
                    break
        if f:
            break
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
from heapq import heapify, heappop, heappush

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# x * xをどう評価するか、heapに「おいしさ」の高い順に入れていく
N, K = lr()
TD = [lr() for _ in range(N)]
heap = []
kind = 0
happy = 0
used = set()
TD.sort(key=lambda x: x[1], reverse=True)
for t, d in TD[:K]:
    if t not in used:
        used.add(t)
        kind += 1
    else:
        heappush(heap, d)
    happy += d

cand = [happy+kind**2]
for t, d in TD[K:]:
    if not heap:
        break
    if t in used:
        continue
    h = heappop(heap)
    happy += (d-h)
    kind += 1
    cand.append(happy+kind**2)

answer = max(cand)
print(answer)