POJ 3304 Segments 判断直线与线段相交

题意:给你一些线段 问你它们的投影有没有一部分可以重叠在一起

思路:投影重叠在一起 其实也就是是否存在一条直线 使得它与所有线段都相交 注意这里相交并不是单纯的规范相交 那么如何判断线段与直线非规范相交呢 我们找到直线上两个点a1 a2 对于一条线段b1 b2如果Cross(a2 - a1, b1 - a1) * Cross(a2 - a1, b2 - a1) < 0 则说明线段两点在直线两端 这属于规范相交 而如果等于零 则说明线段上至少有一个点在直线上 这就是所谓的非规范相交

对于几何题 清晰的思路以及可读性很高的代码是必不可少的(虽然其它题也是这样。。。) 这样在写的过程中会很有逻辑感 而且debug的时候会相对轻松些 这题代码写的也不算好 但起码看起来不会太累 轻松1Y~

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
using namespace std;

#define REP( i, a, b ) for( int i = a; i < b; i++ )

const int maxn = 100 + 10;
const double eps = 1e-8;

struct Point{
          double x, y;
          Point(double x = 0, double y = 0) : x(x), y(y) {}
          bool operator < (const Point &rhs) const{
                    if(fabs(x - rhs.x) < eps) return y < rhs.y;
                    return x < rhs.x;
          }
          void read(){ scanf("%lf%lf", &x, &y); }
};

typedef Point Vector;

int dcmp(double x){
          if(fabs(x) < eps) return 0;
          return x > 0 ? 1 : -1;
}

bool operator == (const Point &A, const Point &B) { return !dcmp(A.x - B.x) && !dcmp(A.y - B.y); }
Point operator - (const Point &A, const Point &B) { return Point(A.x - B.x, A.y - B.y); }
double Cross(const Vector &A, const Vector &B) { return A.x * B.y - A.y * B.x; }

int n;
Point a[maxn], b[maxn];
vector<Point> p;

void input(){
          scanf("%d", &n);
          p.clear();
          REP(i, 0, n){
                    a[i].read(), b[i].read();
                    p.push_back(a[i]);
                    p.push_back(b[i]);
          }
}

bool SegmentLineIntersection(int k, int i, int j){
          return Cross(p[j] - p[i], a[k] - p[i]) * Cross(p[j] - p[i], b[k] - p[i]) <= 0;
}

bool OK(int i, int j){
          REP(k, 0, n)
          if(!SegmentLineIntersection(k, i, j))
                    return false;
          return true;
}

void solve(){
          sort(p.begin(), p.end());
          p.resize(unique(p.begin(), p.end()) - p.begin()); //去重
          REP(i, 0, p.size()) REP(j, i + 1, p.size())
          if( OK(i, j) ){
                    printf("Yes!\n");
                    return;
          }
          printf("No!\n");
}

int main()
{
          //freopen("in.txt", "r", stdin);
          int T;
          scanf("%d", &T);
          while(T--){
                    input();
                    solve();
          }
          return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值