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.
15 10 DZFDFZDFDDDDDDF
82
6 4 YJSNPI
4
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.
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b>a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b<a)a = b; }
const int N = 0, M = 0, Z = 1e9 + 7, ms63 = 0x3f3f3f3f;
int n, k;
int cnt[26];
int main()
{
while (~scanf("%d%d", &n,&k))
{
for (int i = 1; i <= n; ++i)
{
char ch; scanf(" %c", &ch);
ch -= 'A';
++cnt[ch];
}
LL ans = 0;
sort(cnt, cnt + 26);
for (int i = 25; i >= 0; --i)
{
LL take = min(k, cnt[i]);
k -= take;
ans += take*take;
}
printf("%lld\n", ans);
}
return 0;
}
/*
【题意】
给你一个字符串,长度为n(1e5)
我们选其中的k个,使得∑每个字符i(i∈[1,k])*该字符个数尽可能大
【类型】
水题 贪心
【分析】
直接贪心选择数量最多的字符即可
【时间复杂度&&优化】
O(n)
*/