codeforces 462 B.Appleman and Card Game (贪心)

B. Appleman and Card Game
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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

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.

Sample test(s)
input
15 10
DZFDFZDFDDDDDDF
output
82
input
6 4
YJSNPI
output

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值