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:
n,k= map(int,input().split())
tlist=[]
dlist=[]
fulllist = []
for i in range(n):
    t,d= map(int,input().split())
    tlist.append(t)
    dlist.append(d)
    fulllist.append((d,t))
newflist = sorted(fulllist,reverse=True)
basesum = 0
baseadd = []
shurui = set()
basedict = {}
inbase = []
for (c,e) in sorted(newflist[:k],reverse=True):
    basesum+=c
    baseadd.append((c,e))
    if e in shurui:        
        inbase.append((c,e))
    else:
        shurui.add(e)
    basedict[e]=basedict.get(e,[])+[c]
basepoint = basesum + len(shurui)*len(shurui)
if n==k:
    print(basepoint)
else:
    outbase = []
    outset = set()
    for (c,e) in newflist[k:]:
        if (not e in shurui) and (not e in outset):
            outbase.append((c,e))
            outset.add(e)
    koukan = min(len(inbase),len(outbase))
    points=[basepoint]
    g=basepoint
    sh = len(shurui)
    for kout,kin in zip(outbase[:koukan],sorted(inbase[:koukan],reverse=True)):
        newpoint = points[-1]-kin[0]+kout[0] + 2*sh + 1
        sh+=1
        points.append(newpoint)
        g = max(g,newpoint)
    print(g)

Submission status: Wrong Answer

Solution code:
n,k= map(int,input().split())
tlist=[]
dlist=[]
fulllist = []
for i in range(n):
    t,d= map(int,input().split())
    tlist.append(t)
    dlist.append(d)
    fulllist.append((d,t))
newflist = sorted(fulllist,reverse=True)
basesum = 0
baseadd = []
shurui = set()
basedict = {}
inbase = []
for (c,e) in sorted(newflist[:k],reverse=True):
    basesum+=c
    baseadd.append((c,e))
    if e in shurui:        
        inbase.append((c,e))
    else:
        shurui.add(e)
    basedict[e]=basedict.get(e,[])+[c]
basepoint = basesum + len(shurui)*len(shurui)
outbase = []
outset = set()
for (c,e) in newflist[k:]:
    if not e in shurui and not e in outset:
        outbase.append((c,e))
        outset.add(e)
koukan = min(len(inbase),len(outbase))
points=[basepoint]
g=basepoint
sh = len(shurui)
for kin,kout in zip(inbase[:koukan],sorted(outbase[:koukan],reverse=True)):
    newpoint = points[-1]-(kin[0]-kout[0]) + 2*sh + 1
    sh+=1
    points.append(newpoint)
    g = max(g,newpoint)
print(g)

Submission status: Wrong Answer

Solution code:
n,k= map(int,input().split())
fulllist = []
for i in range(n):
    t,d= map(int,input().split())
    fulllist.append((d,t))
newflist = sorted(fulllist,reverse=True)
basesum = 0
baseadd = []
shurui = set()
basedict = {}
inbase = []
for (c,e) in sorted(newflist[:k],reverse=True):
    basesum+=c
    baseadd.append((c,e))
    if e in shurui:inbase.append((c,e))
    else:shurui.add(e)
    basedict[e]=basedict.get(e,[])+[c]
basepoint = basesum + len(shurui)*len(shurui)
outbase = []
for (c,e) in newflist[k:]:
    if not e in shurui:outbase.append((c,e))
koukan = min(len(inbase),len(outbase))
pt = basepoint
g  = basepoint
sh = len(shurui)
for kin,kout in zip(inbase[:koukan],sorted(outbase[:koukan],reverse=True)):
    newpoint = pt - (kin[0]-kout[0]) + 2*sh + 1
    sh+=1
    g = max(g,newpoint)
    pt = newpoint
print(g)

Submission status: Wrong Answer

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

n, k = map(int, input().split())
s = []
for _ in range(n):
    t, d = map(int, input().split())
    s.append((d, t))
s.sort()
bp = 0
x = 0
c = Counter()
cand = []
for _ in range(k):
    d, t = s.pop()
    bp += d
    if c[t] == 0:
        x += 1
    c[t] += 1
    heappush(cand, (d, t))
ans = bp + x * x
while s:
    d, t = s.pop()
    if c[t] == 0:
        while cand:
            dd, td = heappop(cand)
            if c[td] == 1:
                continue
            else:
                c[td] -= 1
                bp -= dd
                break
        else:
            break
        bp += d
        x += 1
        ans = max(ans, bp + x * x)
print(ans)

Submission status: Wrong Answer

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

from collections import deque
n, k = list(map(int, input().split()))

td = [list(map(int, input().split())) for i in range(n)]

td = sorted(td, key=lambda x: x[1], reverse=True)

set_ = set()
val = 0
duplicated = deque([])

for t_tmp, d_tmp in td[:k]:
    val += d_tmp
    if t_tmp in set_:
        duplicated.append(d_tmp)
    else:
        set_.add(t_tmp)

now = val + len(set_)**2


nx = deque(td[k:])
ans = now
c = len(set_)
while len(set_) < k and nx:
    i, j = nx.popleft()
    if i in set_:
        continue
    d = duplicated.pop()
    diff = j-d + 2 * c + 1
    set_.add(i)
    ans = max(now, now + diff)
    now += diff
    c += 1
print(ans)

Submission status: Wrong Answer

Solution code:
import heapq
N, K = map(int,input().split())
L1 = []
L2 = []
S = set()
val = 0

for _ in range(N):
    t, d = map(int,input().split())
    L1.append((d, t))

L1.sort(reverse = True)

for i in range(K):
    val += L1[i][0]
    if L1[i][1] in S:
        heapq.heappush(L2, -L1[i][0])
    else:
        S.add(L1[i][1])

ans = val + len(S) ** 2

for i in range(K, N):
    if len(L2) == 0:
        break
    if not L1[i][1] in S:
        S.add(L1[i][1])
        val += heapq.heappop(L2)
        val += L1[i][0]
        ans = max(ans, val + len(S) ** 2)

print(ans)

Submission status: Wrong Answer

Solution code:
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())
        if len(eat_sushis) > k:
            discard_num = len(eat_sushis) - k
            for _ in range(discard_num):
                eat_sushis.pop()

    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()

Submission status: Wrong Answer

Solution code:
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
            c[t] = 1
        s.append((t,d))

    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()

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

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


while s and q:
    tmp=ans
    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)

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

#show(ate)
#show(init_q,q,ans)

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=max(tmp,ans)
    #heappush(q,(d,t))
    ate[t]=1
    cnt[rt]-=1
    x+=1


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


print(ans)