Description
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.
Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.
Print a single integer – the answer to the problem.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.
Output
Print a single integer – the answer to the problem.
Samples
input
15 10
DZFDFZDFDDDDDDF
output
82
input
6 4
YJSNPI
output
4
Note
In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
题目的意思就是给你n张牌,让你从中选出k张牌,使得你获得硬币最多
硬币=一种牌你选的张数的平方,如果选的牌大于这种牌的数量,那么硬币为这种牌数量的平方
当一种牌选完了,就只能选其他牌了
解题思路
只需要统计每种牌的数量从大到小排序,每次都选出出现次数最多的牌,把硬币累加起来就好了
分两种情况,第一种情况就是k<=某种牌的数量a[i],result+=k*k,第二种情况,k>a[i],k-=a[i](把这种牌全部选完),result+=a[i]*a[i];
#include<iostream>;
#include<cstring>;
#include<algorithm>;
using namespace std;
const int N = 10000;
long long a[N];
bool cmp(int a, int b) {
return a > b;
};
int main() {
int n,max1=1;
long long res = 0,k;
cin >> n >> k;
char w;
for (int i = 1; i <= n; i++) {
cin >> w;
a[w - 'A' + 1]++;//统计每一个字母出现的次数
max1 = max(max1, w - 'A' + 1);//max1代表第一种牌和最后一种牌的距离 共有max1+1种牌
};
sort(a + 1, a +max1+1 , cmp);//将1到max1+1出现过的牌排序
for (int i = 1; i <= max1+1; i++) {
if (k <= a[i]) {//当选取的牌小于这种种类的牌时,最大值就是当前还未选取的牌牌数的平方
res += k * k;
k = 0;
break;
}
else {//当要选的牌数大于当前这种牌牌数时
k -= a[i];//选出a[i]张牌
res += a[i] * a[i];//加上a[i]的平方
};
};
cout << res << endl;
return 0;
};
ac了