fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4.  
  5. int max_coins(const std::vector<int>& deck, int n, int k) {
  6. // Create a frequency map of card types
  7. std::unordered_map<int, int> card_count;
  8. for (int i = 0; i < n; i++) {
  9. card_count[deck[i]]++;
  10. }
  11.  
  12. int coins = 0;
  13.  
  14. // Create the initial hand with the first k cards
  15. std::unordered_map<int, int> hand;
  16. for (int i = 0; i < k; i++) {
  17. hand[deck[i]]++;
  18. card_count[deck[i]]--;
  19. }
  20.  
  21. // Function to count pairs in the given map
  22. auto count_pairs = [](std::unordered_map<int, int>& map) {
  23. int pairs = 0;
  24. for (auto& entry : map) {
  25. pairs += entry.second / 2; // Count how many pairs can be made
  26. }
  27. return pairs;
  28. };
  29.  
  30. coins += count_pairs(hand); // Start by counting pairs in the initial hand
  31.  
  32. int deck_index = k; // Points to the next card in the deck
  33. while (deck_index < n) {
  34. // Two new cards are drawn from the deck
  35. hand[deck[deck_index]]++;
  36. hand[deck[deck_index + 1]]++;
  37. deck_index += 2; // Increment by two as two cards are drawn
  38.  
  39. // Check for pairs in the hand
  40. coins += count_pairs(hand);
  41.  
  42. // Remove pairs from the hand
  43. for (auto it = hand.begin(); it != hand.end();) {
  44. if (it->second >= 2) {
  45. it->second %= 2; // Keep only the remainder if there were pairs
  46. }
  47. if (it->second == 0) {
  48. it = hand.erase(it); // Remove card type from the hand if there are no cards left
  49. } else {
  50. it++;
  51. }
  52. }
  53. }
  54.  
  55. return coins;
  56. }
  57.  
  58. int main() {
  59. int n, k;
  60. std::cin >> n >> k;
  61.  
  62. std::vector<int> deck(n);
  63. for (int i = 0; i < n; i++) {
  64. std::cin >> deck[i];
  65. }
  66.  
  67. std::cout << max_coins(deck, n, k) << std::endl;
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0.01s 5272KB
stdin
4 4
1 2 1 2
stdout
2