[zoj1648]Circuit Board--计算几何,判断两条线段是否相交

题目描述

On the circuit board, there are lots of circuit paths. We know the basic constrain is that no two path cross each other, for otherwise the board will be burned.

Now given a circuit diagram, your task is to lookup if there are some crossed paths. If not find, print “ok!”, otherwise “burned!” in one line.

A circuit path is defined as a line segment on a plane with two endpoints p1(x1,y1) and p2(x2,y2).

You may assume that no two paths will cross each other at any of their endpoints.

Input

The input consists of several test cases. For each case, the first line contains an integer n(<=2000), the number of paths, then followed by n lines each with four float numbers x1, y1, x2, y2.

Output

If there are two paths crossing each other, output “burned!” in one line; otherwise output “ok!” in one line.

Sample Input

1
0 0 1 1
2
0 0 1 1
0 1 1 0

Sample Output

ok!
burned!

题解

这道题目的大概意思就是给你n条线段,要你判断是不是任意两条线段都不相交。

看这道题目的数据,就知道肯定是枚举两条线段判断它们是否相交,现在的问题就转化为了怎么判断两条线段是否相交。

想要判断两条直线是否相交一般需要两个试验来进行判断。

1.快速排斥试验

如果以两条线段为对角线分别作矩形(平行于 x x y y 轴),那么如果这两个矩形不相交,显然这两条线段是不相交的。如果相交,这两条线段也不一定相交,这个大家可以画图画出来,那么进入第二步。

2.跨立试验

如果两条线段相交,那么一条线段的两个端点肯定会在另一条线段的两端了,所以我们就可以直接用矢量叉积非常快速的判断出是否在一条线段的两端了。要记住,叉积等于0的情况是存在的。而且,这个试验的判断必须得在上一个试验满足后才能进行,不然就会出错。

这样这道题目就做完了。下面放代码:

#include
#include
#include
#include
#include
#define maxn 2010
using namespace std;
const double eps=1e-10;
int n;
struct P{
    double x,y;
}a[maxn],b[maxn];
P operator - (P a,P b)
{
    P tmp;
    tmp.x=a.x-b.x;tmp.y=a.y-b.y;
    return tmp;
}
double operator * (P a,P b)
{
    return a.x*b.y-b.x*a.y;
}
bool check(P p1,P p2,P p3,P p4)
{
    if(!(max(p1.x,p2.x)>=min(p3.x,p4.x)+eps&&max(p3.x,p4.x)>=min(p1.x,p2.x)+eps
       &&max(p1.y,p2.y)>=min(p3.y,p4.y)+eps&&max(p3.y,p4.y)>=min(p1.y,p2.y)+eps))  return false;
    if(((p3-p1)*(p2-p1))*((p4-p1)*(p2-p1))>eps)  return false;
    if(((p1-p3)*(p4-p3))*((p2-p3)*(p4-p3))>eps)  return false;
    return true;
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;i++)  scanf("%lf%lf%lf%lf",&a[i].x,&a[i].y,&b[i].x,&b[i].y);
        int flag=0;
        for(int i=1;i<=n;i++){
            for(int j=i+1;j<=n;j++){
                if(check(a[i],b[i],a[j],b[j])==true){
                    flag=1;
                    break;
                }
            }
            if(flag==1)  break;
        }
        if(flag==1){
            puts("burned!");
        }
        else{
            puts("ok!");
        }
    }
    return 0;
}

谢谢大家!!

你可能感兴趣的:(计算几何)