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 C (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<stdio.h>
#include<stdlib.h>

#define max(a,b) ((a)>(b)?(a):(b))

int compare_int(const void *a,const void *b){
	if( *(long long*)b>*(long long*)a)return 1;
	if( *(long long*)b==*(long long*)a)return 0;
	if( *(long long*)b<*(long long*)a)return -1;
}

struct sushi{
	long long d;
	int t;
};

long long heap[100000],sz=0;

void prio_push(long long x){
	int i=sz++;
	while(i>0){
		int p=(i-1)/2;
		if(heap[p]<=x)break;
		heap[i]=heap[p];
		i=p;
	}
	heap[i]=x;
}

long long prio_pop(){
	long long ret=heap[0];
	long long x=heap[--sz];
	int i=0;
	while(i*2+1<sz){
		int a=i*2+1,b=i*2+2;
		if(b<sz&&heap[b]<heap[a])a=b;
		if(heap[a]==x)break;
		heap[i]=heap[a];
		i=a;
	}
	heap[i]=x;
	return ret;
}

long long prio_r(){
	return heap[0];
}

int main(){
	int n,k,i;
	struct sushi td[100000];
	long long ans=0,v=0,anss[100000]={0};
	int va[100001]={0};
	scanf("%d%d",&n,&k);
	for(i=0;i<n;i++)scanf("%d%lld",&td[i].t,&td[i].d);
	qsort(td,n,sizeof(struct sushi),compare_int);
	for(i=0;i<k;i++){
		ans+=td[i].d;
		if(va[td[i].t]>0)prio_push(td[i].d);
		va[td[i].t]++;
	}
	for(i=0;i<=n;i++)v+=(va[i]>0?1:0);
	int vv=v;
	for(i=0;i<=n;i++)anss[i]=ans;
	for(i=k;i<n;i++){
		if(va[td[i].t]==0&&sz>0&&v<=k){
			long long tmp=prio_pop();
			v++;
			anss[v]=anss[v-1]-tmp+td[i].d;
			va[td[i].t]++;
//			anss[v]+=v*v;
		}
	}
	for(i=vv;i<=v;i++)ans=max(ans,anss[i]+i*i);
	printf("%lld\n",ans);
	return 0;
}