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 in PyPy3 (2.4.0) (judge verdict: Wrong Answer)

#!/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()