【題解】TIOJ 1231 . 寵物雞問題

【題目敘述】https://tioj.ck.tp.edu.tw/problems/1231

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;

int n, k;
long long ans;
vector <pii> v;

bool cmp(pii x, pii y){
    if (x.first != y.first) return x.first < y.first;
    return x.second > y.second;
}
priority_queue <int, vector<int>, greater<int>> pq;

int main(){
    cin >> n;
    for (int i = 0, a, b; i < n; i++){
        cin >> a >> b;
        v.push_back({b, a});
    }
    cin >> k;
    sort(v.begin(), v.end(), cmp);
    for (auto [t, a]:v){
        if (t > pq.size() && pq.size() < k){
            pq.push(a);
            ans += a;
        }
        else if (a > pq.top()){
            ans -= pq.top();
            pq.pop();
            pq.push(a);
            ans += a;
        }
    }
    cout << ans-(k-pq.size()) << "\n";
}
分享本文 Share with friends