3633. 双人旋转赛车

Sun_shine

二分判定答案(n)+大根堆存储前n个数,复杂度为O(nlgn)

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
using ll = long long;

const int MAX = 1000000;
int arr[MAX];
int n, k;

bool binraryAns(int ans) {
    priority_queue<int, vector<int>, greater<int>> a;
    ll sumX{}, sumO{ k };
    for (int i = 0; i < ans; i++) {
        a.push(arr[i]);
        sumX += arr[i];
    }
    if (sumX >= sumO) return true; // Maybe less.
    else {
        for (int i = ans; i < n; i++) {
            if (arr[i] > a.top()) {
                sumX -= a.top();
                sumO += a.top();
                a.pop();
                sumX += arr[i];
                a.push(arr[i]);
                if (sumX >= sumO) return true;
            }
            else sumO += arr[i];
        }
    }
    return false; //Maybe more
}

int main() {
    cin >> n >> k;
    for (int i = 0; i < n; i++) scanf("%d", arr + i);
    int l = 1, r = n;
    while (l < r) {
        int mid = (l + r) >> 1;
        if (binraryAns(mid)) r = mid;
        else l = mid + 1;
    }
    if (!binraryAns(l)) printf("-1\n");
    else printf("%d\n", l);
}
你当前正在回复 博客/题目
存在问题!