题解 | #请客吃饭#
请客吃饭
https://www.nowcoder.com/practice/4250a369235e414ba9128bb23ff4fcf5
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iomanip>
#include <stack>
#include <numeric>
#include <ctime>
#include <string>
#include <bitset>
#include <unordered_map>
#include <unordered_set>
using namespace std;
using ll = long long;
const ll N = 2e5 + 5, mod = 1e9 + 7, inf = 0x3f3f3f3f;
pair<ll, ll>a[N];
ll n, k;
bool check(ll mid) {
ll maxx = -inf, minn = inf, sum = 0;
queue<pair<ll, ll>>q;
for (int i = 1; i <= n; i++) {
ll x = a[i].first, y = a[i].second;
q.push(a[i]);
sum += y;
while (!q.empty() && q.front().first < x - mid) {
sum -= q.front().second;
q.pop();
}
maxx = max(maxx, sum);
}
return maxx >= k;
}
void solve() {
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i].first;
}
for (int i = 1; i <= n; i++) {
cin >> a[i].second;
}
sort(a + 1, a + 1 + n);
ll l = 0, r = 1e12;
ll ans = 2e18;
while (l <= r) {
ll mid = l + r >> 1;
if (check(mid)) {
r = mid - 1;
ans = mid;
} else {
l = mid + 1;
}
}
cout << (ans == 2e18 ? -1 : ans);
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}

