POJ 3304

POJ 3304

計算幾何基礎,叉積應用

大意是給出n條線段,問是否存在一條直線使得所有線段投影到直線上後存在至少一個公共點。其實就是判斷是否存在一條直線與所有線段相交。
畫圖稍加分析可以發現,如果存在一條直線與所有線段相交,我們可以轉動這條直線與至少兩個線段端點重合,也就是說,我們可以通過枚舉兩個端點來確定一條直線,再判斷它是否與所有線段相交。
枚舉端點O(n^2),判斷與線段相交O(n),總體時間複雜度O(n^3),對於n不超過100的規模,可以接受。
判斷直線與線段相交只要兩個端點分別與直線做叉積,線段兩個端點相對於直線的方位相同則說明線段沒有橫跨直線,即不相交。除此,在枚舉點時要注意判斷是否重合,|dx|

#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#define mm0(a) memset(a,0,sizeof(a));
#define debug puts("It's ok here!")
using namespace std;
const int maxn=5e3+5;
const double eps=1e-8;
struct Point{
    double x, y;
    Point(){}
    Point(double _x, double _y):x(_x), y(_y){}
};
struct line{
    Point s, t;
    line(){}
    line(double sx,double sy,double tx,double ty){s.x=sx; s.y=sy; t.x=tx; t.y=ty;}
    line(Point _s, Point _t):s(_s), t(_t){}
};
int dcmp(double x){
    if(fabs(x)<eps) return 0;
    return x<0?-1:1;
}
double cross(Point a,Point b,Point c){
    return (a.x-c.x)*(b.y-c.y)-(a.y-c.y)*(b.x-c.x);
}
bool crossleft(Point a,Point b,Point c){
    return cross(a, b, c)>0;
}
double dis(Point a,Point b){
    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
Point P[maxn];
line Seg[maxn];
int n, m;
bool ok(Point a,Point b){
    for(int i=0;i<n;i++)
    if(dcmp(cross(Seg[i].s,a,b)*cross(Seg[i].t,a,b))>0)
        return false;
    return true;
}
int main()
{
    double x1, y1, x2, y2;
    int T=0;

    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%lf%lf%lf%lf",&x1, &y1, &x2, &y2);
            P[2*i]=Point(x1,y1), P[2*i+1]=Point(x2,y2);
            Seg[i]=line(P[2*i],P[2*i+1]);
        }
        int flag=0;
        for(int i=0;i<2*n;i++)
        for(int j=i+1;j<2*n;j++)
        if((dcmp(P[i].x-P[j].x)!=0||dcmp(P[i].y-P[j].y)!=0)&&ok(P[i],P[j])){
            flag=1;
        }
        if(flag) puts("Yes!");
        else puts("No!");
    }

    return 0;
}
發佈了54 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章