POJ 3304 Segments (直线与所有线段相交)

题意:找到一条直线使得所有线段在直线上的投影至少有一个公共点,若存在,yes,不存在,no。

题解:直线与所有线段相交
若所有线段在直线上投影有一公共点,那么过该公共点作这条直线的垂线,该垂线必然与所有线段相交,所以只要找到一条直线能相交所有线段即可。

对于一条相交所有线段的直线,该直线经过平移、旋转必然结果两条线段的两个端点,所以我们枚举任意两条线段,共4种连线可能,枚举判断与所有线段是否相交即可。

n可能为1,循环时注意一下即可。
连线时可能两点重合,判断一下距离是否为0。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
//二维计算几何模板
const double eps = 1e-8;
const double inf = 1e20;
const double pi = acos(-1.0);
//Compares a double to zero
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 distance(Point p) {
        return hypot(x-p.x, y-p.y);
    }
};
struct Line {
    Point s, e;
    Line() {}
    Line(Point _s, Point _e) {
        s = _s;
        e = _e;
    }
    //求线段长度
    double length() {
        return s.distance(e);
    }
    //直线和线段相交判断
    //-*this line -v seg
    //2 规范相交
    //1 非规范相交
    //0 不相交
    int linecrossseg(Line v) {
        int d1 = sgn((e-s) ^ (v.s-s));
        int d2 = sgn((e-s) ^ (v.e-s));
        if ((d1 ^ d2) == -2) return 2;
        return (d1 == 0 || d2 == 0);
    }
};
int t, n;
double xa, ya, xb, yb;
Line line[111];
bool check(Line l) {
    if (sgn(l.length()) == 0) return false;    //重合
    for (int i = 0; i < n; i++) {
        if (l.linecrossseg(line[i]) == 0) return false;
    }
    return true;
}
int main() {
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        for (int i = 0; i < n; i++) {
            scanf("%lf%lf%lf%lf", &xa, &ya, &xb, &yb);
            line[i] = Line(Point(xa, ya), Point(xb, yb));
        }
        int flag = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                if (check(Line(line[i].s, line[j].s)) ||
                    check(Line(line[i].s, line[j].e)) ||
                    check(Line(line[i].e, line[j].s)) ||
                    check(Line(line[i].e, line[j].e))) {
                    flag = 1;
                    break;
                }
            }
            if (flag) break;
        }
        if (flag) puts("Yes!");
        else puts("No!");
    }
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值