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代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+5; 4 typedef long long LL; 5 int n,k,cnt[26];char str[maxn];LL m;//这里要用long long,因为10^10溢出int最大值 6 int main(){ 7 while(~scanf("%d%d",&n,&k)){ 8 memset(cnt,0,sizeof(cnt)); 9 getchar();//吃掉回车符就字符串得影响 10 scanf("%s",str); 11 for(int i=0;i<(int)strlen(str);++i)cnt[str[i]-'A']++;//映射:对应字母出现的次数 12 sort(cnt,cnt+26);m=0; 13 for(int i=25;i>=0;--i){//从大往小贪心 14 if(k>=cnt[i]){m+=(LL)cnt[i]*cnt[i];k-=cnt[i];}//累加所取字母个数的平方 15 else{m+=k*k;k=0;} 16 } 17 cout<<m<<endl; 18 } 19 return 0; 20 }