fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <queue>
  5. #include <unordered_map>
  6. #include <cmath>
  7.  
  8. using namespace std;
  9.  
  10. int minStringValue(int K, const string& S) {
  11. vector<int> freq(26, 0);
  12. for (char ch : S) {
  13. freq[ch - 'A']++;
  14. }
  15.  
  16. priority_queue<int> pq;
  17. for (int f : freq) {
  18. if (f > 0) pq.push(f);
  19. }
  20.  
  21. while (K-- && !pq.empty()) {
  22. int top = pq.top(); pq.pop();
  23. top--;
  24. if (top > 0) pq.push(top);
  25. }
  26.  
  27. int result = 0;
  28. while (!pq.empty()) {
  29. int f = pq.top(); pq.pop();
  30. result += f * f;
  31. }
  32.  
  33. return result;
  34. }
  35.  
  36. int main() {
  37. int T;
  38. cin >> T;
  39. while (T--) {
  40. int K;
  41. string S;
  42. cin >> K >> S;
  43. cout << minStringValue(K, S) << endl;
  44. }
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5288KB
stdin
2

0

ABCC

1

ABCC
stdout
6
3