UVa 1555 - Garland

链接

传送门

题意

\(n\)座灯塔,第一个高度为\(a\),第\(n\)个高度为\(b\),其余的高度满足公式\(h[i]=(h[i-1]+h[i+1])/2+1\),给出\(a\),求最小的\(b\)

思路

二分第二个灯塔的高度,然后可以计算出所有灯塔的高度,取\(b\)的最小值。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;

const int inf = 0x3f3f3f3f;
const double eps = 1e-4;
int n;
double a, b;

bool judge(double h) {
double cur = h, pre = a;
for (int i = 2; i < n; i++) {
h = cur;
cur = 2 * cur + 2 - pre;
if (cur < 0) return false;
pre = h;
}
b = cur;
return true;
}
int main() {
while (~scanf("%d%lf", &n, &a)) {
double l = 0, r = a, pre = -inf;
while (l < r) {
double m = (l + r) / 2;
if (judge(m)) {
if (fabs(pre - b) < eps) {
break;
}
pre = b;
r = m;
}
else {
l = m;
}
}
printf("%.2lf\n", b);
}
return 0;
}