Ultraviolet-1616 Caravan Robbers binary + brute force conversion
N line segments are given, and each line segment is converted into a line segment of the original line segment, so that all the line segments after the change are long and not intersecting, and the maximum output length is
Solution: To solve this problem, we need to use long double to ensure accuracy and high accuracy. Next we need to convert the number of long double to the result of division of two integers. There are two ways to solve this problem.
#include
#include#include
using namespace std;#define maxn 100010#define esp 1e-11struct Line{ int L, R;}line[maxn];int n;bool ok(long double len) { long double cur = 0.0, t; for(int i = 0; i < n; i++) { t = line[i].L * 1.0; cur = max(t, cur); if(cur + len - line[i].R > esp) return false; cur += len; } return true;}bool cmp(const Line a, const Line b) { if(a.L == b.L) return a.R < b.R; return a.L < b.L;}int main() { while(scanf("%d", &n) != EOF) { for(int i = 0; i < n; i++) scanf("%d%d", &line[i].L, &line[i].R); sort(line, line + n, cmp); long double L = 0.0, R = line[n - 1].R + esp; while(R - L > esp) { long double mid = (L + R) / 2; if(ok(mid)) L = mid; else R = mid; } /* int i; for(i = 1; i <= n + 1; i++) { int p = (int)(L * i + 0.5); long double t = p * 1.0 / i; if(t - L < 2 * esp && L - t < esp * 2) break; } printf("%d/%d\n", (int)(L * i + 0.5), i); */ long double Min = 0x3f3f3f3f; int p, q; for(int i = 1; i <= maxn; i++) { int j = floor(L * i); if(fabs((long double)(j) / i - L) < Min) { p = j; q = i; Min = fabs((long double)(j) / i - L); } j = ceil(L * i); if(fabs((long double)(j) / i - L) < Min) { p = j; q = i; Min = fabs((long double)(j) / i - L); } } printf("%d/%d\n", p, q); } return 0;}