#include <iostream> #include <vector> #include <map> #include <algorithm> int main() { int n; std::cin >> n; std::map<int, int> counts; for (int i = 0; i < n; i++) { int input; std::cin >> input; counts[input]++; } int total = n; int result = 0; std::vector<std::pair<int, int>> pairs; for (auto itr = counts.begin(); itr != counts.end(); ++itr) { pairs.push_back(*itr); } sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second < b.second; } ); while (total > 0) { auto max = pairs.back(); if (max.second > 1) { int maxCount = max.second; pairs.pop_back(); total -= maxCount; while (maxCount - 1 > 0 && total > 0) { auto min = pairs.front(); int minCount = min.second; if (minCount < maxCount) { pairs.erase(pairs.begin()); total -= minCount; maxCount -= minCount; } else { min.second -= maxCount - 1; total -= maxCount - 1; maxCount = 0; } } result++; } else { result += total; total = 0; } } std::cout << result; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <iostream> #include <vector> #include <map> #include <algorithm> int main() { int n; std::cin >> n; std::map<int, int> counts; for (int i = 0; i < n; i++) { int input; std::cin >> input; counts[input]++; } int total = n; int result = 0; std::vector<std::pair<int, int>> pairs; for (auto itr = counts.begin(); itr != counts.end(); ++itr) { pairs.push_back(*itr); } sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second < b.second; } ); while (total > 0) { auto max = pairs.back(); if (max.second > 1) { int maxCount = max.second; pairs.pop_back(); total -= maxCount; while (maxCount - 1 > 0 && total > 0) { auto min = pairs.front(); int minCount = min.second; if (minCount < maxCount) { pairs.erase(pairs.begin()); total -= minCount; maxCount -= minCount; } else { min.second -= maxCount - 1; total -= maxCount - 1; maxCount = 0; } } result++; } else { result += total; total = 0; } } std::cout << result; } |