有一个宽度为1的管道,一束光从左端射入问最远能到达的横坐标是多少
我的做法是把管道分为上半部分线段和下半部分线段,光线射入角度就是枚举管道拐点,然后从左到右判断上半部分的线段是否在光线的上面,如果不是则说明光线在这里被阻挡了,下半部分同理,最后取上下部分被阻挡点的最小值,就是此次枚举所能到达的横坐标
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const double eps = 1e-8;
const int inf = 0x3f3f3f3f;
const int mx = 105;
int n;
double left, ans;
struct Point {
double x, y;
}pt[mx];
struct Line {
double x1, y1, x2, y2;
Line() {};
Line(double _x1, double _y1, double _x2, double _y2) {
x1 = _x1; x2 = _x2; y1 = _y1; y2 = _y2;
}
}up[mx], down[mx];
double cross(double x1, double y1, double x2, double y2) {
return x1*y2 - x2*y1;
}
double calc(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
return 1.0*((x1*y2-x2*y1)*(x3-x4) - (x3*y4-x4*y3)*(x1-x2)) / ((y2-y1)*(x3-x4) - (x2-x1)*(y3-y4));
}
bool judge(double x1, double y1, double x2, double y2) {
if (cross(pt[2].x-x1, pt[2].y-y1, x2-x1, y2-y1)*
cross(pt[1].x-x1, pt[1].y-y1, x2-x1, y2-y1) > eps)
return false;
for (int i = 2; i <= n; i++) {
if(cross(x1-up[i].x1, y1-up[i].y1, x2-up[i].x1, y2-up[i].y1) > -eps
&& cross(x1-up[i].x2, y1-up[i].y2, x2-up[i].x2, y2-up[i].y2) > -eps)
continue;
double tmp = calc(up[i].x1, up[i].y1, up[i].x2, up[i].y2, x1, y1, x2, y2);
left = min(left, tmp);
break;
}
for (int i = 2; i <= n; i++) {
if(cross(x1-down[i].x1, y1-down[i].y1, x2-down[i].x1, y2-down[i].y1) < eps
&& cross(x1-down[i].x2, y1-down[i].y2, x2-down[i].x2, y2-down[i].y2) < eps)
continue;
double tmp = calc(down[i].x1, down[i].y1, down[i].x2, down[i].y2, x1, y1, x2, y2);
left = min(left, tmp);
break;
}
return true;
}
void solve() {
ans = -inf;
for (int i = 1; i <= 2*n; i++) {
for (int j = i+1; j <= 2*n; j++) {
left = inf;
if (pt[i].x == pt[j].x) continue;
if (judge(pt[i].x, pt[i].y, pt[j].x, pt[j].y))
ans = max(ans, left);
}
}
}
int main() {
while (scanf("%d", &n) != EOF && n != 0) {
for (int i = 1; i <= n; i++) {
scanf("%lf %lf", &pt[i*2].x, &pt[i*2].y);
pt[i*2-1].x = pt[i*2].x; pt[i*2-1].y = pt[i*2].y - 1;
if (i >= 2) {
up[i] = Line(pt[i*2-2].x, pt[i*2-2].y, pt[i*2].x, pt[i*2].y);
down[i] = Line(pt[i*2-3].x, pt[i*2-3].y, pt[i*2-1].x, pt[i*2-1].y);
}
}
solve();
if (inf - ans < eps) puts("Through all the pipe.");
else printf("%.2f\n", ans);
}
return 0;
}