Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma GCC Optimize("Ofast")
- #include <bits/stdc++.h>
- #define all(x) begin(x),end(x)
- using namespace std;
- using ld = long double;
- using ll = long long;
- const bool LOCAL = true;
- void solve() {
- int n, k;
- cin >> n >> k;
- vector<pair<int, int>> arr(n);
- map<int, map<int, int>> weightToCountedColors; // weight -> {color -> count}
- for (int i = 0; i < n; i++) {
- cin >> arr[i].first >> arr[i].second; // weight, color
- weightToCountedColors[arr[i].first][arr[i].second]++;
- }
- // block = a set of elements with the same weight
- // multiblock = block with elements with at least two different colors
- // simpleblock = block with elements with only one color (<=> number of elements in the block is one)
- vector<pair<int, map<int, int>>> blocks;
- for (auto &element: weightToCountedColors) {
- auto &weight = element.first;
- auto &block = element.second;
- if (block.size() >= 2) {
- blocks.emplace_back(weight, block); // current block is multiblock
- continue;
- }
- block.begin()->second = 1; // current block is a simpleblock, so we need to set number of elements to 1
- int currentColor = block.begin()->first;
- if (blocks.empty() || blocks.back().second.size() >= 2) {
- blocks.emplace_back(weight, block); // previous block is a multiblock or it is first element
- continue;
- }
- if (blocks.back().second.begin()->first == currentColor) {
- blocks.back().first = weight; // previous block is a simpleblock with the same color as current
- } else {
- blocks.emplace_back(weight, block); // previous block is a simpleblock with another color
- }
- }
- // The size of answer must be equal to at most k
- long long answer = 0;
- int currentSize = 0;
- for (auto it = blocks.rbegin(); it != blocks.rend(); it++) {
- auto &weight = it->first;
- auto &block = it->second;
- for (auto element: block) {
- auto count = element.second;
- currentSize += count;
- answer += 1ll * count * weight;
- }
- if (currentSize >= k) {
- while (currentSize > k) {
- currentSize--;
- answer -= weight;
- }
- break;
- }
- }
- cout << answer << '\n';
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- if (LOCAL) {
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- }
- solve();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement