题解 | #请客吃饭#

请客吃饭

https://www.nowcoder.com/practice/4250a369235e414ba9128bb23ff4fcf5

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

typedef long long ll;

bool check(const vector<pair<int, int>>& friends, ll mid, ll k) {
    int n = friends.size();
    ll total_joy = 0;
    int left = 0;
    for (int right = 0; right < n; ++right) {
        // 维持窗口的隔阂值不超过 mid
        while (friends[right].first - friends[left].first > mid) {
            total_joy -= friends[left].second;
            ++left;
        }
        // 加入当前右端点的愉悦值
        total_joy += friends[right].second;
        // 检查是否满足条件
        if (total_joy >= k) return true;
    }
    return false;
}

int main() {
    int n;
    ll k;
    cin >> n >> k;
    vector<pair<int, int>> friends(n);
    for (int i = 0; i < n; ++i) cin >> friends[i].first;
    for (int i = 0; i < n; ++i) cin >> friends[i].second;

    // 按财富值排序
    sort(friends.begin(), friends.end());

    // 二分查找隔阂值
    ll left = 0, right = 1e9, result = -1;
    while (left <= right) {
        ll mid = left + (right - left) / 2;
        if (check(friends, mid, k)) {
            result = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }

    cout << result << endl;
    return 0;
}

全部评论

相关推荐

Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
努力学习的小绵羊:我反倒觉得这种挺好的,给不到我想要的就别浪费大家时间了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务