POJ 2653 && HDU 1147 Pick-up sticks(计算几何)

本文介绍了一种通过线段相交算法解决木条覆盖问题的方法。该问题要求找出一组木条中哪些木条最终没有被其他木条覆盖。通过枚举每根木条并检查是否有后续木条与之相交来确定未被覆盖的木条。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
有n根木条,一根一根的往一个坐标系上丢(给出木条两点的坐标),问最后不被覆盖的木条有哪些,即丢的木条如果和前面丢的木条交叉的话,就会覆盖前面那根木条
Input
多组用例,每组用例第一行为木条数n,之后n行每行四个浮点数表示木条两端坐标,以n=0结束输入
Output
对于每组用例,输出最后不被覆盖的木条
Sample Input
5
1 1 4 2
2 3 3 1
1 -2.0 8 4
1 4 8 2
3 3 6 -2.0
3
0 0 1 1
1 0 2 1
2 0 3 1
0
Sample Output
Top sticks: 2, 4, 5.
Top sticks: 1, 2, 3.
Solution
枚举每根木条,如果它后面的木条有与其相交的则将其标记,最后没被标记的就是未被覆盖的木条
Code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const double eps = 1e-8;
#define maxn 111111
int sgn(double x)
{
    if(fabs(x)<eps)return 0;
    if(x<0)return -1;
    else return 1;
}
struct Point
{
    double x,y;
    Point(){}
    Point(double _x,double _y)
    {
        x=_x;y=_y;
    }
    Point operator -(const Point &b)const
    {
        return Point(x-b.x,y-b.y);
    }
    double operator ^(const Point &b)const
    {
        return x*b.y-y*b.x;
    }
    double operator *(const Point &b)const
    {
        return x*b.x+y*b.y;
    }
};
struct Line
{
    Point s,e;
    Line(){}
    Line(Point _s,Point _e)
    {
        s=_s;e=_e;
    }
};
//判断线段相交
bool inter(Line l1,Line l2)
{
    return 
        max(l1.s.x,l1.e.x)>=min(l2.s.x,l2.e.x)&&
        max(l2.s.x,l2.e.x)>=min(l1.s.x,l1.e.x)&&
        max(l1.s.y,l1.e.y)>=min(l2.s.y,l2.e.y)&&
        max(l2.s.y,l2.e.y)>=min(l1.s.y,l1.e.y)&&
        sgn((l2.s-l1.s)^(l1.e-l1.s))*sgn((l2.e-l1.s)^(l1.e-l1.s))<=0&&
        sgn((l1.s-l2.s)^(l2.e-l2.s))*sgn((l1.e-l2.s)^(l2.e-l2.s))<=0;
}
Line line[maxn];
bool flag[maxn];
int main()
{
    int n;
    double x1,x2,y1,y2;
    while(scanf("%d",&n),n)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            line[i]=Line(Point(x1,y1),Point(x2,y2));
            flag[i]=true;
        }
        for(int i=1;i<=n;i++)
            for(int j=i+1;j<=n;j++)
                if(inter(line[i],line[j]))
                {
                    flag[i]=false;
                    break;
                }
        printf("Top sticks: ");
        bool res=true;
        for(int i=1;i<=n;i++)
            if(flag[i])
            {
                if(res)
                    res=false;
                else
                    printf(", ");
                printf("%d",i);
            }
        printf(".\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值