标签:
题目大意:给出n条线段,把每条线段变成原来线段的一条子线段,使得改变后的所有线段等长且不相交,输出最大长度
解题思路:这题要用long double确保精度,精度要求很高,接下来就是将这个long double的数转化为两个整数相除的结果了,有两种方法,学习到了
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
#define maxn 100010
#define esp 1e-11
struct 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;
}
UVA - 1616 Caravan Robbers 二分+暴力转换
标签:
原文地址:http://blog.csdn.net/l123012013048/article/details/45512703