题解 | #请客吃饭#
请客吃饭
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; }