POJ 1039 Pipe (计算几何)

可以证明最终结果一定过边界上的两个点,因为如果未过两个点,可以把直线旋转成过两个点并使结果更优。

枚举两点,先求出该直线和a[1],b[1]所在直线的交点,如果在a[1],b[1]之间说明是合法的。然后依次判断与a[i],b[i]直线的交点,看在不在两点之间,如果不在,若大于a[1],说明于a[i],a[i-1]相交了,反之就是和下面的线段相交了,求出交点就是结果。

注意判断实数大小用eps


代码:

//
//  main.cpp
//  1039 pipe
//
//  Created by Baoli1100 on 15/4/3.
//  Copyright (c) 2015年 Baoli1100. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define eps 1e-5
#define INF 1e8
using namespace std;
int N;
bool flag=0;
struct Point{
    double x,y;
    Point operator *(double t){
        Point k;
        k.x=x*t;k.y=y*t;
        return k;
    }
    Point(){}
    Point(double x,double y):x(x),y(y){}
};
Point a[25],b[25];

Point operator -(Point a,Point b){
    return Point(a.x-b.x,a.y-b.y);
}

Point operator +(Point a,Point b){
    return Point(b.x+a.x,b.y+a.y);
}
bool operator ==(Point a,Point b){
    return fabs(a.x-b.x)<eps&&fabs(a.y-b.y)<eps;
}
int dcmp(double n){
    if(fabs(n)<eps) return 0;
    else if(n<0) return -1;
    else return 1;
}

double Cross(Point a,Point b){
    return a.x*b.y-a.y*b.x;
}


Point GetIntsect(Point a1,Point a2,Point b1,Point b2){
    Point u=a1-b1;
    Point v1=a2-a1,v2=b2-b1;
    double t=Cross(v2,u)/Cross(v1,v2);
    return a1+v1*t;
}

double solve(int s,int t){
    Point Ints=GetIntsect(a[1],b[1],a[s],b[t]);
    if(dcmp(Ints.y-a[1].y)>0||dcmp(Ints.y-b[1].y)<0) return -INF;
    for(int i=2;i<=N;i++){
        Ints=GetIntsect(a[i],b[i],a[s],b[t]);
        if(dcmp(Ints.y-a[i].y)>0){
            Point tmp=GetIntsect(a[i-1],a[i],a[s],b[t]);
            return tmp.x;
        }
        if(dcmp(Ints.y-b[i].y)<0){
            Point tmp=GetIntsect(b[i-1],b[i],a[s],b[t]);
            return tmp.x;
        }
    }
    return INF;
}

int main(){
    while(~scanf("%d",&N)){
        if(!N) break;
        for(int i=1;i<=N;i++){
            scanf("%lf%lf",&a[i].x,&a[i].y);
            b[i].x=a[i].x;b[i].y=a[i].y-1;
        }
        flag=0;
        double res=-INF;
        for(int i=1;i<=N;i++){
            if(flag) break;
            for(int j=i+1;j<=N;j++){
                res=max(solve(i,j),res);
                res=max(solve(j,i),res);
                if(res==INF){
                    flag=1;
                    break;
                }
            }
        }
        if(flag){
            printf("Through all the pipe.\n");
        }
        else printf("%.2f\n",res);
    }
    return 0;
}


你可能感兴趣的:(两直线交点)