题目:点击打开链接
该题目就是判断两条直线是否相交的模板题目,通过这个我又认识了一波模板。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const double eps=1e-10;
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
return x<0?-1:1;
}
struct Point
{
double x,y;
Point() {}
Point(double x,double y):x(x),y(y) {}
};
typedef Point Vector;
Vector operator-(Point A,Point B)
{
return Vector(A.x-B.x,A.y-B.y);
}
double Dot(Vector A,Vector B)
{
return A.x*B.x+A.y*B.y;
}
double Cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
bool InSegment(Point P,Point A,Point B)
{
return dcmp(Cross(A-P,B-P))==0 && dcmp(Dot(A-P,B-P))<=0;
}
bool SegmentIntersection(Point a1,Point a2,Point b1,Point b2)
{
double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);
if(dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0) return true;
if(dcmp(c1)==0 && InSegment(b1,a1,a2)) return true;
if(dcmp(c2)==0 && InSegment(b2,a1,a2)) return true;
if(dcmp(c3)==0 && InSegment(a1,b1,b2)) return true;
if(dcmp(c4)==0 && InSegment(a2,b1,b2)) return true;
return false;
}
/***刘汝佳模板***/
const int maxn=10+5;
Point seg[maxn][2];
int fa[maxn];
int findset(int x)
{
return fa[x]==-1?x: fa[x]=findset(fa[x]);
}
void bind(int i,int j)
{
int fi=findset(i);
int fj=findset(j);
if(fi!=fj) fa[fi]=fj;
}
int main()
{
int n;
while(scanf("%d",&n)==1 && n)
{
for(int i=1; i<=n; ++i)
scanf("%lf%lf%lf%lf",&seg[i][0].x,&seg[i][0].y,&seg[i][1].x,&seg[i][1].y);
memset(fa,-1,sizeof(fa));
for(int i=1; i<=n; ++i)
for(int j=i+1; j<=n; ++j)
if(SegmentIntersection(seg[i][0],seg[i][1],seg[j][0],seg[j][1]))
bind(i,j);
int i,j;
while(scanf("%d%d",&i,&j)==2)
{
if(i==0 && j==0) break;
if(findset(i)==findset(j)) printf("CONNECTED\n");
else printf("NOT CONNECTED\n");
}
}
return 0;
}
上面完全就是模板。