计算几何初涉 例题:Pipe

问题:黑书P359页。

有一个宽度为1的折线管道,上面顶点为(x0,y0).......(xn,yn),下面各顶点为(x0,y0-1)......(xn,yn-1),假设管壁不透明,不反射,光线从最左边的(x0,y0) (x0,y0-1)之间射入,向四面八方传播,问光线最远能射到哪里或着能穿透整个管道。

1.最优光线必须是擦到一个上顶点一个下顶点。

2.枚举算法,任取一个上顶点和一个下顶点,形成直线L,若L能射穿入口,则是一条可行的光线,在从左向右判断是否相交的管壁交点,并不断更新保存,如果和所有管壁都不与L相交,说明L射穿了整个管道。

#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <stdio.h>
#include <vector>
using namespace std;

#define max(a,b) ((a)>(b)?(a):(b))

const double INF = 999999999.0;

int dblcmp(double d)//控制精度
{
    if(fabs(d) < 1e-11)
        return 0;
    return (d>0)?1:-1;
}

struct point
{
    double x,y;
};

double det(double x1,double y1,double x2,double y2)
{
    return x1*y2-x2*y1;
}

double cross(point a,point b,point c)
{
    return det(b.x-a.x,b.y-a.y,c.x-a.x,c.y-a.y);
}

int segcross(point a,point b,point c,point d,point &p)//判断AB这条直线是否和CD线段相交
{
    double s1,s2;
    int d1,d2;

    d1 = dblcmp(s1=cross(a,b,c));
    d2 = dblcmp(s2=cross(a,b,d));

    if(d1*d2<0)
    {
        p.x = (c.x*s2-d.x*s1)/(s2-s1);
        return 1;
    }
    if(d1==0)//经过拐点
    {
        p.x = c.x;
        return 1;
    }
    if(d2==0)//经过拐点
    {
        p.x = d.x;
        return 1;
    }
    return 0;
}

int main()
{
    point record;
    int n,i,j,k;
    while(scanf("%d",&n) == 1 && n)
    {
        vector<point> up(n);
        vector<point> down(n);
        up.clear();
        down.clear();
        for(i = 0; i < n; i++)
        {
            scanf("%lf%lf",&up[i].x,&up[i].y);
            down[i].x = up[i].x;
            down[i].y = up[i].y-1;
        }

        double res = -INF;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < n; j++)
            {
                for(k = 0; k < n; k++)
                {
                    if( !segcross(up[i],down[j],up[k],down[k],record) )//未穿过( up[k], down[k] )直线
                    {
                        break;
                    }
                }
                if(k == n)//穿过了所有( up[k], down[k] ),则穿过了整个管道
                    res = -1;
                else if(k > max(i,j))//未穿过,但是是合法的光线,寻找最远交点
                {
                    record.x = -INF;
                    segcross(up[i],down[j],up[k-1],up[k],record);//判断是否与上壁相交。
                    if(record.x > res)  res = record.x;
                    segcross(up[i],down[j],down[k-1],down[k],record);//判断是否与下壁相交。
                    if(record.x > res)    res = record.x;
                }
            }
        }
        if(res ==  -1)
            printf("Through all the pipe.\n");
        else
            printf("%.2lf\n",res);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值