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.

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)

import heapq


class PriorityQueue:
    class Reverse:
        def __init__(self, val):
            self.val = val

        def __lt__(self, other):
            return self.val > other.val

        def __repr__(self):
            return repr(self.val)

    def __init__(self, x=None, desc=False):
        if not x:
            x = []
        if desc:
            for i in range(len(x)):
                x[i] = self.Reverse(x[i])
        self._desc = desc
        self._container = x
        heapq.heapify(self._container)

    @property
    def is_empty(self):
        return not self._container

    def pop(self):
        if self._desc:
            return heapq.heappop(self._container).val
        else:
            return heapq.heappop(self._container)

    def push(self, item):
        if self._desc:
            heapq.heappush(self._container, self.Reverse(item))
        else:
            heapq.heappush(self._container, item)

    def top(self):
        if self._desc:
            return self._container[0].val
        else:
            return self._container[0]

    def sum(self):
        return sum(self._container)

    def __len__(self):
        return len(self._container)


def main():
    from operator import itemgetter

    n, k = list(map(int, readline().split()))
    sushis_original = [list(map(int, readline().split())) for _ in range(n)]

    sushis_original.sort(key=itemgetter(1))
    sushis_original.sort(key=itemgetter(0))

    new_type = 0
    prev = -1
    for i in range(n):
        cur = sushis_original[i][0]
        if prev != cur:
            new_type += 1
        if cur > new_type:
            sushis_original[i][0] = new_type
        prev = cur

    type_num = sushis_original[-1][0]

    sushis = {i: [] for i in range(1, type_num + 1)}

    for sushi_type, val in sushis_original:
        sushis[sushi_type].append(val)

    eat_sushis = PriorityQueue()
    rem_sushis = PriorityQueue(desc=True)
    rem = k

    if rem >= type_num:
        for i in range(1, type_num + 1):
            eat_sushis.push(sushis[i].pop())
        rem -= type_num
        for vals in sushis.values():
            for val in vals:
                rem_sushis.push(val)
        for _ in range(rem):
            eat_sushis.push(rem_sushis.pop())
    else:
        for i in range(1, type_num + 1):
            eat_sushis.push(sushis[i].pop())
        discard_num = type_num - k
        for _ in range(discard_num):
            eat_sushis.pop()
        for vals in sushis.values():
            for val in vals:
                rem_sushis.push(val)

    cur_type = min(k, type_num)
    sub_next = 2 * cur_type - 1

    while rem_sushis:
        cur_val = eat_sushis.top()
        new_val = rem_sushis.top()
        diff = new_val - cur_val
        if diff >= sub_next:
            eat_sushis.pop()
            eat_sushis.push(rem_sushis.pop())
            cur_type -= 1
            sub_next = 2 * cur_type - 1
        else:
            break

    ans = cur_type ** 2 + eat_sushis.sum()

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import heapq
N,K = map(int,input().split())

L = [[] for _ in range(N)]
All = []
s = set([])
for i in range(N):
  t,d = map(int,input().split())
  t-=1 
  heapq.heappush(L[t], -d) 
  heapq.heappush(All,[-d,t]) 
  s.add(t)


point = 0
ns = 0 
later = []
now = []
syurui = set([])
while len(now) < K and All:
  temp = heapq.heappop(All)
  if temp[1] not in syurui:
    ns += 1
    point -= temp[0]
    syurui.add(temp[1])
    heapq.heappush(now, -1*temp[0])
  else:
    later.append(temp)
for i in later:
  heapq.heappush(All,i)

point += ns*ns
while len(now) < K:
  temp = heapq.heappop(All)
  point -= temp[0]
  heapq.heappush(now, -1*temp[0])



while All and now[0] < -1*All[0][0]:
  temp = heapq.heappop(All)
  dele = heapq.heappop(now)
  
  upoint = point - temp[0] - dele - ns*ns + (ns-1)**2
  
  if upoint >= point:
    point = upoint
    ns -= 1
  else:
    break
    
print(point)

Solution (Python):
N,K = map(int,input().split())
A = sorted([list(map(int,input().split())) for _ in range(N)],key=lambda x:x[1],reverse=True)
C = {}
tot1 = 0
for i in range(K):
    t,d = A[i]
    if t not in C:
        C[t] = 0
    C[t] += 1
    tot1 += d
tot2 = len(C)
tot = tot1+tot2**2
cur = K
for i in range(K-1,-1,-1):
    t,d = A[i]
    if C[t]>1:
        tot1 -= d
        C[t] -= 1
        j = cur
        while j<N:
            t1,d1 = A[j]
            if t1 not in C:
                C[t1]=1
                tot1 += d1
                tot2 += 1
                if tot1+tot2**2>tot:
                    tot = tot1+tot2**2
                cur = j+1
                break
            else:
                j += 1
                cur = j
print(tot)

Solution (Python):
import heapq
N,K = map(int, input().split())
L = [[] for _ in range(N)]
h = []
for _ in range(N):
    t,d = map(int, input().split())
    L[t-1].append(d)
    heapq.heappush(h, (-d, t-1))

cnt = 0
for l in L:
    if len(l) > 0:
        cnt += 1

used = [0]*N
h1 = []
h2 = []
num = 0
if K <= cnt:
    while len(h2) < K:
        temp = heapq.heappop(h)
        if used[temp[1]] > 0:
            heapq.heappush(h1, temp)
            continue
        used[temp[1]] += 1
        heapq.heappush(h2, (-temp[0], temp[1]))
        num -= temp[0]
else:
    c2 = 0
    while len(h2) < K:
        temp = heapq.heappop(h)
        if used[temp[1]] > 0:
            if c2 < K-cnt:
                c2 += 1
            else:
                heapq.heappush(h1, temp)
                continue
        used[temp[1]] += 1
        heapq.heappush(h2, (-temp[0], temp[1]))
        num -= temp[0]

cnt = min(K, cnt)
ans = num + cnt**2
while len(h1) > 0 and h2[0][0] < -h1[0][0]:
    t1 = heapq.heappop(h1)
    t2 = heapq.heappop(h2)
    used[t2[1]] -= 1
    used[t1[1]] += 1
    if used[t2[1]] == 0:
        cnt -= 1
    if used[t1[1]] == 1:
        cnt += 1
    num += -t1[0]-t2[0]
    ans = max(ans, num+cnt**2)
    heapq.heappush(h2, (-t1[0], t1[1]))

print(ans)

Solution (Python):
from collections import Counter

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

TD.sort(reverse=True, key=lambda a: a[1])

A = TD[:K]

B = []
V = set()
for t, d in TD:
    if t in V:
        continue
    B.append((t, d))
    V.add(t)

cntT = Counter([t for t, _ in A])
V = set(cntT.keys())
S = sum([d for _, d in A])
B = [(t, d) for t, d in B if not t in V]

C = []
for t, d in A[::-1]:
    if cntT[t] > 1:
        C.append((t, d))
        cntT[t] -= 1

C = C[::-1]
ans = S + len(V)**2
for t, d in B:
    if not C:
        break
    _, less = C.pop()
    S -= less
    S += d
    V.add(t)
    ans = max(ans, S + len(V)**2)
print(ans)

Solution (Python):
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N,K = LI()
    V = [LI() for _ in range(N)]
    V.sort(key=lambda x:x[1],reverse=True)
    c = [0] * (N+1)
    s = []
    ans = 0
    cnt = 0
    for t,d in V[:K]:
        ans += d
        if c[t] == 0:
            ans += 1 + 2*cnt
            cnt += 1
        else:
            s.append((t,d))
        c[t] = 1

    tmp = ans
    for t,d in V[K:]:
        if s == []: break
        if c[t] == 0:
            x,y = s.pop()
            tmp += d + cnt * 2 + 1 - y
            c[t] = 1
            cnt += 1
            ans = max(tmp,ans)
    print(ans)





if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
import heapq
n, k = map(int, input().split())
TD = sorted([list(map(int, input().split())) for _ in range(n)], reverse=True, key=itemgetter(1))
L = [[] for _ in range(n+1)]
P = []
a = 0
cnt = 0
F = [-float("inf")]*(n+1)
for t, d in TD[:k]:
  L[t].append(d)
  if len(L[t]) == 1:
    a += 1
  cnt += d
F[a] = cnt
for i in range(1, n+1):
  while len(L[i]) > 1:
    heapq.heappush(P, L[i].pop())
now = k
for i in range(a, n):
  if len(P) == 0:
    break
  while now < n and L[TD[now][0]]:
    now += 1
  if now == n:
    break
  t, d = TD[now]
  L[t].append(d)
  F[i+1] = F[i] - heapq.heappop(P) + d
ans = 0
for i in range(a, n+1):
  ans = max(ans, F[i] + i*i)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
import heapq
n, k = map(int, input().split())
TD = sorted([list(map(int, input().split())) for _ in range(n)], reverse=True, key=itemgetter(1))
L = [[] for _ in range(n+1)]
P = []
a = 0
cnt = 0
F = [-float("inf")]*(n+1)
B = 0
for t, d in TD[:k]:
  if B>>t & 1:
    heapq.heappush(P, d)
  else:
    B |= 1 << t
    a += 1
  cnt += d
F[a] = cnt
for i in range(a, n):
  if len(P) == 0:
    break
  while k < n and B>>TD[k][0] & 1:
    k += 1
  if k == n:
    break
  t, d = TD[k]
  B |= 1 << t
  F[i+1] = F[i] - heapq.heappop(P) + d
ans = 0
for i in range(a, n+1):
  ans = max(ans, F[i] + i*i)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
import heapq
n, k = map(int, input().split())
TD = sorted([list(map(int, input().split())) for _ in range(n)], reverse=True, key=itemgetter(1))
L = [[] for _ in range(n+1)]
P = []
a = 0
cnt = 0
F = [-float("inf")]*(n+1)
B = 0
for t, d in TD[:k]:
  if B>>t & 1:
    heapq.heappush(P, d)
  else:
    B |= 1 << t
    a += 1
  cnt += d
F[a] = cnt
for i in range(a, n):
  if len(P) == 0:
    break
  while k < n and B>>TD[k][0] & 1:
    k += 1
  if k == n:
    break
  t, d = TD[k]
  B |= 1 << t
  F[i+1] = F[i] - heapq.heappop(P) + d
ans = 0
for i in range(a, n+1):
  ans = max(ans, F[i] + i*i)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
import heapq
n, k = map(int, input().split())
TD = sorted([list(map(int, input().split())) for _ in range(n)], reverse=True, key=itemgetter(1))
L = [[] for _ in range(n+1)]
P = []
a = 0
cnt = 0
F = [-float("inf")]*(n+1)
for t, d in TD[:k]:
  L[t].append(d)
  if len(L[t]) == 1:
    a += 1
  cnt += d
F[a] = cnt
for i in range(1, n+1):
  while len(L[i]) > 1:
    heapq.heappush(P, L[i].pop())
now = k
for i in range(a, n):
  if len(P) == 0:
    break
  while now < n and L[TD[now][0]]:
    now += 1
  if now == n:
    break
  t, d = TD[now]
  L[t].append(d)
  F[i+1] = F[i] - heapq.heappop(P) + d
ans = 0
for i in range(a, n+1):
  ans = max(ans, F[i] + i*i)
print(ans)

Solution (Python):
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={'

    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

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: 
    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]
    
    
    def query(self,l,r):
        if r>self.size:r=self.size
        
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    
    def query_id(self,l,r):
        if r>self.size:r=self.size
        
        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
for i in range(k):
    d,t=s.pop()
    ate[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

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

    ans=max(tmp,ans)
    ate[t]=1
    x+=1

print(ans)

Solution (Python):

import sys
input = sys.stdin.readline









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




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


ans = 0
s = set() 
r = list() 
for i in range(K):
    t,d = TD[i]
    ans += d
    if t not in s:
        s.add(t) 
    else:
        r.append(TD[i])
ans += len(s)**2

Ans = ans


for i in range(K,N):
    t0,d0 = TD[i]
    
    if t0 not in s and len(r) > 0:
        
        t1,d1 = r.pop()
        
        ans = ans - d1 + d0 - len(s)**2 + (len(s)+1)**2
        
        s.add(t0)
        
        Ans = max(Ans,ans)

print(Ans)

Solution (Python):
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(ti)

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)

Solution (Python):
from collections import defaultdict

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

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


tmp = [[] for _ in range(N + 1)]
cnt = defaultdict(int)
out_candidate = []
kiso = 0
kind = 0
for i in range(K):
    t, d = TD[i]
    tmp[t].append(d)
    if cnt[t]:
        out_candidate.append([t, d])
    else:
        kind += 1
    kiso += d
    cnt[t] += 1
out_candidate.sort(key = lambda x: -x[1])





answer = []
answer.append(kiso + kind ** 2)

in_candidate = []
if K < N:
    for i in range(K, N):
        in_candidate.append(TD[i])
in_candidate.sort(key = lambda x: x[1])


while out_candidate and in_candidate:
    in_t, in_d = in_candidate.pop()
    if cnt[in_t] == 0:
        cnt[in_t] += 1
        out_t, out_d = out_candidate.pop()
        kiso += in_d - out_d
        kind += 1
        answer.append(kiso + kind ** 2)
        
print(max(answer))

Solution (Python):

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:
        if dup_index >= 0:
            point -= duplication[dup_index][1]
            dup_index -= 1
            point += sushi[i][1]
            sushi_kind.add(sushi[i][0])
    ans = max(ans, point + pow(len(sushi_kind),2))
print(ans)

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()


def main():
    N, K = map(int, input().split())
    sushi = []
    neta = set([])
    for _ in range(N):
        t, d = map(int, input().split())
        sushi.append((d, t))
        neta.add(t)
    sushi.sort()
    L = len(neta)

    eat_kind = set([])
    same_kind = []
    point = 0
    for _ in range(K):
        d, t = sushi.pop()
        point += d
        if t not in eat_kind:
            eat_kind.add(t)
        else:
            same_kind.append((d, t))
    l = len(eat_kind)
    point += l ** 2
    

    """
    貪欲でおいしいもの順にネタを取った後、新しい種類のネタにどんどんスイッチしていく方針はあっていたのに
    実装がヘビーになりすぎるから考えを間違っているだろうと撤退したのが愚かだった...!
    
    今は実装力を上げるパートということですね。
    """

    remain = [(d, t) for d, t in sushi if t not in eat_kind]
    remain.sort()
    
    val = point 
    for i in range(l, L): 
        val = val - i ** 2 + (i + 1) ** 2
        if not same_kind: break
        pre_d, _ = same_kind.pop()
        val -= pre_d
        if not remain: break
        d, t = remain.pop()
        while t in eat_kind: d, t = remain.pop()
        val += d
        eat_kind.add(t)
        point = max(point, val)
        

    print(point)

    



if __name__ == "__main__":
    main()

Solution (Python):

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
fix = 0
var = []
len_var = 0
sum_var = 0
tmp_max = 0

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

print(ans)

Solution (Python):
from heapq import heappush,heappop,heapify

n,k = map(int,input().split())









td = []
for i in range(n):
  td.append(tuple(map(int,input().split())))
td.sort(key = lambda x:(x[0],-x[1]))

tf = [False for _ in range(n)]
s = []
for t,d in td:
  t -= 1
  if tf[t]:
    s.append((0,d)) 
  else:
    s.append((1,d)) 
    tf[t] = True

s.sort(key = lambda x:-x[1])

hq = s[:k]
heapify(hq)

rhq = []
for t,d in s[k:]:
  if t == 1:
    rhq.append(-d)
heapify(rhq)

ans = 0
tsum = 0
dsum = 0
for t,d in hq:
  tsum += t
  dsum += d
ans = dsum+tsum**2

while(True):
  t,d = heappop(hq)
  if t == 1:
    break
  if len(rhq) == 0:
    break
  newd = heappop(rhq)
  dsum += -newd-d
  tsum += 1
  ans = max(dsum+tsum**2,ans)
print(ans)

Solution (Python):
from collections import defaultdict
import heapq
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
U = 10 ** 5 + 1

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

DT.sort(reverse=True)
score = 0
kind = defaultdict(list)
used = [0] * (U + 1)
for d, t in DT[:K]:
    score += d
    used[t] += 1
    kind[t].append(d)

cnt = len(kind)
ans = score + (cnt * cnt)

cand = []  
for key, val in kind.items():
    val.sort(reverse=True)
    while len(val) > 1:
        heapq.heappush(cand, (val.pop(), key))


for d_in, t_in in DT[K:]:
    if not cand:
        break
    if used[t_in]:
        continue

    d_out, t_out = heapq.heappop(cand)
    used[t_in] += 1
    used[t_out] -= 1
    cnt += 1
    score = score - d_out + d_in
    ans = max(ans, score + (cnt * cnt))

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(100000000)

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

    sushi.sort(key = lambda x:x[1],reverse = True)
    ans = 0
    dic = {}
    change = []
    for a,b in sushi[:K]:
        if a in dic:
            dic[a].append(b)
            change.append((a,b))
        else:
            dic[a] = [b]
        ans += b

    various = len(dic)
    ans += various ** 2
    ret = ans
    used_type = set(dic.keys())
    suggestion = [p for p in sushi[K:] if p[0] not in used_type]
    for a,b in suggestion:
        if len(change) == 0:
            break
        if a in used_type:
            continue
        dic[change[-1][0]].pop()
        ret -= change[-1][1]
        ret += b + 2*various + 1
        dic[a] = b
        change.pop()
        various += 1
        used_type.add(a)
        ans = max(ans,ret)
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque                
from heapq import heapify, heappush, heappop 
 
 
def main():
    sys.setrecursionlimit(10**6)    
    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])
    
    
    
    
    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()[0] + (2 * group_size + 1) - delicious
            ans = max(ans, prev + diff)
            prev += diff
            group_size += 1
            group_num[neta] -= 1
            
    print(ans)
 
 
 
if __name__ == "__main__":
    main()

Solution (Python):
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()
doubled = []
rest = []
points = 0
for i, n in enumerate(nums):
    if i < K:
        if not n[1] in se:
            se.add(n[1])
        else:
            doubled.append(n)
        points += n[0]
    else:
        rest.append(n)
ans = points + pow(len(se), 2)
idx = len(doubled)-1
for d, t in rest:
    if idx < 0: break
    if t in se: continue
    points -= doubled[idx][0]
    idx -= 1
    points += d
    se.add(t)
    ans = max(ans, points+pow(len(se), 2))
print(ans)

Solution (Python):
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()
doubled = []
rest = []
points = 0
for i, n in enumerate(nums):
    if i < K:
        if not n[1] in se:
            se.add(n[1])
        else:
            doubled.append(n)
        points += n[0]
    else:
        rest.append(n)
ans = points + pow(len(se), 2)
idx = len(doubled)-1
for d, t in rest:
    if idx < 0: break
    if t in se: continue
    points -= doubled[idx][0]
    idx -= 1
    points += d
    se.add(t)
    ans = max(ans, points+pow(len(se), 2))
print(ans)

Solution (Python):
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()
idx2 = 0
for i, (d, t) in enumerate(rest):
    if t in se: continue
    if len(a2) <= idx2: break
    points -= a2[idx2][0]
    idx2 += 1
    points += d
    se.add(t)
    ans = max(ans, points+pow(len(se), 2))
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
nums = [[] for i in range(N)]
for i in range(N):
    t, d = map(int, input().split())
    t -= 1
    nums[t].append(d)
maxs = []
rest = []
for i in range(N):
    if len(nums[i]) == 0: continue
    nums[i].sort(reverse=True)
    maxs.append(nums[i][0])
    for n in nums[i][1:]:
        rest.append(n)
maxs.sort(reverse=True)
rest.sort(reverse=True)
if len(maxs) > K:
    maxs = maxs[:K]
other = []
idx = 0
while len(maxs)+len(other) < K:
    other.append(rest[idx])
    idx += 1
rest = rest[idx:]

types = len(maxs)
for i,r in enumerate(rest):
    diff = types*types - pow(types-1, 2)
    if diff < r-maxs[len(maxs)-1-i]:
        maxs[len(maxs)-1-i] = r
        types -= 1
    else:
        break
ans = types*types
for num in maxs:
    ans += num
for num in other:
    ans += num
print(ans)