ACM_Appleman and Card Game(简单贪心)

时间:2023-03-10 06:35:41
ACM_Appleman and Card Game(简单贪心)

Appleman and Card Game

Time Limit: 2000/1000ms (Java/Others)

Problem 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?

Input:

Input contains multiple test cases. The first line contains two integers n and k (1 ≤ k ≤ n ≤ 10^5). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.

Output:

For each cases, Print a single integer – the answer to the problem.
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.

Sample Input:

15 10
DZFDFZDFDDDDDDF
6 4
YJSNPI

Sample Output:

82
4
解题思路:简单的贪心,先统计每个字母出现的次数,再排序,最后从次数最多到最小进行贪心,水过!
AC代码:
 #include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+;
typedef long long LL;
int n,k,cnt[];char str[maxn];LL m;//这里要用long long,因为10^10溢出int最大值
int main(){
while(~scanf("%d%d",&n,&k)){
memset(cnt,,sizeof(cnt));
getchar();//吃掉回车符就字符串得影响
scanf("%s",str);
for(int i=;i<(int)strlen(str);++i)cnt[str[i]-'A']++;//映射:对应字母出现的次数
sort(cnt,cnt+);m=;
for(int i=;i>=;--i){//从大往小贪心
if(k>=cnt[i]){m+=(LL)cnt[i]*cnt[i];k-=cnt[i];}//累加所取字母个数的平方
else{m+=k*k;k=;}
}
cout<<m<<endl;
}
return ;
}