CodeForces 462B Appleman and Card Game 贪心

原题: http://codeforces.com/problemset/problem/462/B

题目:

Appleman and Card Game
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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
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.

思路:

输入共有的n个物品和要买的m个物品。
如果买的m个物品中有x个A物品,那么A物品的价格就是x。

比如现在有4个A,3个B,要买6个物品。
买3个A和3个B的方案要花费9+9=18元。
买4个A和2个B的方案要花费16+4=20元。

因为我们要求的是固定了n的个数,求组成n的一些数的平方和的最大值。
看下面一个图:
这里写图片描述
显然,分解成的数越多,越小,最后的值就会越小。

所以我们要一来就放最大的,每次也拿最多的填充,这样才能得到最优解。

注意取值范围,n^2的和可能会int溢出。

代码:

#include <iostream>
#include"stdlib.h"
#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;
typedef long long int lint;
const lint N =100050;
char a[N];
lint num[256];
int cmp(int a,int b)
{
    return a>b;
}
int main()
{
    lint n;
    lint m;
    while(scanf("%I64d %I64d",&n,&m)!=EOF)
    {
        memset(a,0,sizeof(a));
        memset(num,0,sizeof(num));
        scanf("%s",a);
        for(lint i=0; i<n; i++)
        {
            num[a[i]]++;
        }
        sort(num,num+256,cmp);
        lint ans=0;
        int i=0;
        while(num[i]<=m)
        {
            ans=num[i]*num[i]+ans;
            m=m-num[i];
            i++;
        }
        ans=ans+m*m;
        printf("%I64d\n",ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值