版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liufengwei1/article/details/86557896
判断能否找到一条直线使得与每个线段有交点
先枚举2条线段,再枚举出2条线段上的各一个端点,来当做直线。
判断直线相交直接利用向量线段表示法,然后用叉积去算
a是直线的一个点,v是方向向量,b是线段的一个点,w是方向向量
假设a+tv是交点
cj(a + tv − b,w) = 0
cj(a − b,w) + cj(tv,w) = 0
t ∗ cj(v,w) = cj(b − a,w)
t = cj(b − a,w)/cj(v,w)
a+tv的x,y坐标就知道了
还要特别注意如果w是垂直的话,就要判断y坐标是否在b线段内
不然直接用x坐标判断
找到了一条这样的直线直接返回
#include<cstdio>
#include<cstring>
#include<cmath>
#define maxl 100010
#define eps 1e-8
using namespace std;
int sgn(double x)
{
if(fabs(x)<eps) return 0;
if(x<0)
return -1;
else
return 1;
}
struct point
{
double x,y;
point(double a=0,double b=0)
{
x=a;y=b;
}
point operator - (const point &b)const
{
return point(x-b.x,y-b.y);
}
double operator * (const point &b)const
{
return 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
{
if(sgn(x)==0)
return y/b.y;
else
return x/b.x;
}
};
struct line
{
point s,e;
line(point a=point(),point b=point())
{
s=a;e=b;
}
};
int n;
line a[maxl];
int ans[maxl];
bool top[maxl];
inline void prework()
{
point p1,p2;
for(int i=1;i<=n;i++)
{
scanf("%lf%lf%lf%lf",&p1.x,&p1.y,&p2.x,&p2.y);
a[i].s=p1;a[i].e=p2;
top[i]=true;
}
}
inline bool cross(line l1,line l2)
{
line vec=line(l1.s,l1.e-l1.s);
if(((l2.s-vec.s)^vec.e)*(vec.e^(l2.e-vec.s))<0-eps)
return false;
if( ((l2.s-l1.s)^(l2.e-l1.s))*((l2.s-l1.e)^(l2.e-l1.e)) >0+eps)
return false;
if(sgn((l1.e-l1.s)^(l2.e-l2.s))==0)// 平行或重合
if(sgn((l2.s-l1.s)^(l2.e-l1.s))==0) //重合
{
double t1=(l2.s-l1.s)/vec.e;
double t2=(l2.e-l1.s)/vec.e;
if(t1>0-eps && t1<1+eps)
return true;
else if(t2>0-eps &&t2<1+eps)
return true;
else
return false;
}
return true;
}
inline void mainwork()
{
ans[0]=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
if(cross(a[i],a[j]))
{
top[i]=false;
break;
}
if(top[i])
ans[++ans[0]]=i;
}
}
inline void print()
{
printf("Top sticks:");
for(int i=1;i<=ans[0];i++)
printf(" %d%c",ans[i],(i==ans[0])?'.':',');
puts("");
}
int main()
{
while(~scanf("%d",&n) && n)
{
prework();
mainwork();
print();
}
return 0;
}