题目链接:自动刷题机
思路
二分典题,两个二分判断出可能的最大值和最小值。需要注意当删掉y行代码后,当前代码行数小于0时需要将代码行数重新赋值为0,然后需要注意二分的n最大值的边界,因为x[i]的最大值为1e9,日志最多有1e5行,所以考虑极限情况,日志每一行都是写了1e9行代码,所以最大n可能为1e14,尽量将二分的r边界设大。
代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 10;
ll operate[N], l, k;
ll check(ll x) {
ll num = 0, ans = 0;
for (int i = 1; i <= l; i++) {
num += operate[i];
if (num < 0) {
num = 0;
}
if (num >= x) {
ans++;
num = 0;
}
}
return ans;
}
int main() {
cin >> l >> k;
for (int i = 1; i <= l; i++) {
cin >> operate[i];
}
ll nl = 1, nr = 1e18, mid = (nl + nr) >> 1, maxres = -1, minres = -1;
while (nl <= nr) {
mid = (nl + nr) >> 1;
if (check(mid) >= k) {
if (check(mid) == k)
maxres = mid;
nl = mid + 1;
} else {
nr = mid - 1;
}
}
nl = 1, nr = 1e18;
while (nl <= nr) {
mid = (nl + nr) >> 1;
if (check(mid) <= k) {
// 可能会出现只有check>k的情况,没有等于k,但是答案被赋值了,会直接输出,但是实际上结果为-1
if (check(mid) == k)
minres = mid;
nr = mid - 1;
} else {
nl = mid + 1;
}
}
if (maxres == -1) {
cout << -1 << endl;
} else
cout << minres << " " << maxres << endl;
return 0;
}
标签:nl,int,ll,mid,P4343,洛谷,nr,check,刷题
From: https://www.cnblogs.com/againss/p/18250506