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
题解:
题意很简单:给你一个字符串含有n个字符(只含大写字母),从中选出k个字符是的自己所得的分数最大,分数的判定规则为,自己所得的每种相同字母的个数即为该种字母每个所得的分数,比如;得到的字母是DDDDDDDDDF那么所得的分时是9*9+1*1=82;
题意明白了,那么这个题就是一个简单的贪心了,因为(a+b)^2=a^2+b^2+2ab>a^2+b^2,每一次都尽量选个数多的就好了,给所有字母的个数排序就好了。
这里注意还有一个坑,这里的最长数列是10^5那么平方后就是10^10已经超出了int的范围,所以答案要用long long
题目链接:http://codeforces.com/problemset/problem/462/B
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<vector>
#define EPS 1e-6
#define LL long long
using namespace std;
const LL N = 110000;
int main(){
char str[N];
LL num[100]={0};
LL n,m;
scanf("%I64d%I64d",&n,&m);
getchar();
gets(str);
//int len=strlen(str);
for(LL i=0;i<n;i++){
num[str[i]-'A']++;
}
sort(num,num+26);
long long ans=0;
for(LL i=25;i>=0;i--){
if(num[i]<=m) ans=ans+num[i]*num[i],m=m-num[i];
else ans=ans+m*m,m=0;
if(m==0) break;
}
printf("%I64d\n",ans);
return 0;
}