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)

# -*- coding: utf-8 -*-
 
n, k = map(int, input().split())
 
sushi_list = []
neta_set = set()
for i in range(n):
    t, d = map(int, input().split())
    sushi_list.append((t, d))
    neta_set.add(t)
 
sushi_list.sort(key=lambda tup: tup[1])
 
max_sushi_list, rest_of_sushi = sushi_list[-k:], sushi_list[:-k]
max_neta_set = {sushi[0] for sushi in max_sushi_list}
 
iMax = len(neta_set)
iMin = len(max_neta_set)
 
max_score = iMin**2 + sum([sushi[1] for sushi in max_sushi_list])
 
 
for nNeta in range(iMin+1, iMax + 1, 1):
 
    # Find sushi having minimum oishisa and being not unique for neta
    r = len(max_sushi_list)
    swap_index = -1
    for i in range(r):
        if max_sushi_list[i][0] in [neta for neta,oishisa in max_sushi_list[:i]+max_sushi_list[i+1:]]:
            swap_index = i
            break
 
    # Find sushi having maximum oishisa and unique for neta
    r = len(rest_of_sushi)
    for i in range(r):
        if not rest_of_sushi[r-i-1][0] in max_neta_set:
            rest_of_sushi.append(max_sushi_list.pop(swap_index))
            max_sushi_list.append(rest_of_sushi.pop(r-i-1))
            break
 
    score = nNeta**2 + sum([sushi[1] for sushi in max_sushi_list])
    if score > max_score:
      max_score = score
    sushi_list.sort(key=lambda tup: tup[1])
    max_neta_set = {sushi[0] for sushi in max_sushi_list}
 
print(max_score)