P4343 自动做题机
题目大意
对于一个数有如下操作,增加一个数字或减少一个数字每次,每到n就清零并计数,若小于零就变成0,现在操作了k次,给你计数的次数,求n的最小值和最大值。
思路
观察到答案符合单调性,所以直接使用二分答案
代码
#include <bits/stdc++.h>
#define MAX (100000 + 7)
#define long long long
using namespace std;
int N, k, a[MAX];
long l, r, ans1 = -1, ans2 = -1;
long work(long im)
{
int ans = 0; long sum = 0;
for (int i = 1; i <= N; i++)
{
sum = max(sum + a[i], 0ll);
if (sum >= im) sum = 0, ans++;
}return ans;
}
int main()
{
scanf("%d%d", &N, &k);
for (int i = 1; i <= N; i++)
scanf("%d", a + i);
l = 1, r = 1e18;
while (l <= r)
{
long mid = (l + r) >> 1;
if (work(mid) <= k)
{
r = mid - 1;
if (work(mid) == k) ans1 = mid;
}
else l = mid + 1;
}
l = 1, r = 1e18;
while (l <= r)
{
long mid = (l + r) >> 1;
if (work(mid) >= k)
{
l = mid + 1;
if (work(mid) == k) ans2 = mid;
}
else r = mid - 1;
}
if (ans1 == -1) puts("-1");
else printf("%lld %lld\n", ans1, ans2);
}