水池
Building an Aquarium
题目描述
You love fish, that's why you have decided to build an aquarium. You have a piece of coral made of
- Pick an integer
— the height of the tank. Build walls of height on either side of the tank. - Then, fill the tank up with water so that the height of each column is
, unless the coral is taller than ; then no water should be added to this column.
For example, with You can use at most
你需要修一个水池,水池的底部高低不一,第
如果修了一个高
- 对于第
格,需要向其注水 个单位的水,如果 ,则不用注水。 - 水可以有剩余,但不能少,少了就无法修建高度为
的水池。
你一共有
By @Larryyu
输入格式
The first line contains a single integer
The first line of each test case contains two positive integers
The second line of each test case contains
The sum of
首先说明第一行包含一个整数
每个测试用例的第一行包含两个正整数
每个测试用例的第二行包含
输出格式
For each test case, output a single positive integer
We have a proof that under these constraints, such a value of
对于每个测试用例,输出一个正整数
我们有一个证明,在这些约束条件下,这样的值
样例 #1
样例输入 #1
5
7 9
3 1 2 4 6 2 5
3 10
1 1 1
4 1
1 4 3 4
6 1984
2 6 5 9 1 8
1 1000000000
1
样例输出 #1
4
4
2
335
1000000001
提示
The first test case is pictured in the statement. With
In the second test case, we can pick
In the third test case, we can pick
第一个测试案例如语句所示。在 h=4 的情况下,我们需要 8 个单位的水,但如果 h 增加到 5 ,我们需要 13 个单位的水,比 x=9 多。因此, h=4 是最佳方案。
在第二个测试案例中,我们可以选择 h=4 ,并在每列中添加 3 个单位,总共使用 9 个单位的水。可以证明这是最佳方案。
在第三个测试案例中,我们可以选择 h=2 ,并使用所有的水,因此这是最优方案。
题解
和上一题砍树类似,用二分查找即可
#include <cstdio>
int main()
{
int t;scanf("%d", &t);
while (t--)
{
int left = 0, mid = 0;
int n, x; scanf("%d %d", &n, &x);
int a[200005] = {0};
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
long long right = 2e9+10;
while (left <= right)
{
mid = left + (right - left)/2;
long long sum = 0;
for (int i = 0; i < n; i++)
if (mid >= a[i]){sum += mid - a[i];if(sum > x)break;}
if (sum > x)right = mid-1;
else left = mid + 1;
}
printf("%d\n", right);
}
return 0;
}