首页 > 代码库 > Codeforces 263B. Appleman and Card Game

Codeforces 263B. 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
 
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.

 

解题:贪心。

 

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib>10 #include <string>11 #include <set>12 #include <stack>13 #define LL long long14 #define pii pair<int,int>15 #define INF 0x3f3f3f3f16 using namespace std;17 int letter[27];18 char str[100100];19 bool cmp(const int &x,const int &y){20     return x > y;21 }22 int main() {23     int n,k;24     LL ans;25     while(~scanf("%d %d",&n,&k)){26         memset(letter,0,sizeof(letter));27         scanf("%s",str);28         for(int i = 0; str[i]; i++) letter[str[i]-A]++;29         sort(letter,letter+26,cmp);30         for(int i = ans = 0; k && i < 26; i++){31             ans += 1LL*min(k,letter[i])*min(k,letter[i]);32             k -= min(k,letter[i]);33         }34         cout<<ans<<endl;35     }36     return 0;37 }
View Code

 

Codeforces 263B. Appleman and Card Game