您的位置:首页 > 其它

nyoj1132promise me a medal【线段相交判定+求交点】

2015-09-22 16:06 465 查看


promise me a medal

时间限制:1000 ms  |  内存限制:65535 KB
难度:2

描述

  you all know that creat2012 will go to a regional. and i want you all pray for us. thx.

  for this problem, you need judge if two segments is intersection(相交的). if intersect(相交), print yes and the point. else print no.

  easy ? ac it.

输入
T <= 100 cases

8 real numbers (double)

promise two segments is no coincidence.
输出
no

or yes and two real number (one decimal)
样例输入
2
0 0 2 2 1 0 3 2
0 0 2 2 0 2 2 0


样例输出
no
yes 1.0 1.0


题意:给两个线段判断是否相交并求交点

解题思路:由于求交点代码不够完善在求交点时如果两条线段首尾相连且共线无法求出交点需要另外判断因为这个wa了3次一直以为是精度出问题了。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#define eps 1e-10
using namespace std;
double MAX(double a,double b){
return a>b?a:b;
}
double MIN(double a,double b){
return a<b?a:b;
}
struct point{
double x,y;
};
struct line{
point a,b;
}A[2];
bool judge(int a,int b){
if(MIN(A[a].a.x,A[a].b.x)>MAX(A[b].a.x,A[b].b.x)||MIN(A[a].a.y,A[a].b.y)>MAX(A[b].a.y,A[b].b.y)||MIN(A[b].a.x,A[b].b.x)>MAX(A[a].a.x,A[a].b.x)||MIN(A[b].a.y,A[b].b.y)>MAX(A[a].a.y,A[a].b.y))
return false;
double h,i,j,k;
h=(A[a].b.x-A[a].a.x)*(A[b].a.y-A[a].a.y)-(A[a].b.y-A[a].a.y)*(A[b].a.x-A[a].a.x);
i=(A[a].b.x-A[a].a.x)*(A[b].b.y-A[a].a.y)-(A[a].b.y-A[a].a.y)*(A[b].b.x-A[a].a.x);
j=(A[b].b.x-A[b].a.x)*(A[a].a.y-A[b].a.y)-(A[b].b.y-A[b].a.y)*(A[a].a.x-A[b].a.x);
k=(A[b].b.x-A[b].a.x)*(A[a].b.y-A[b].a.y)-(A[b].b.y-A[b].a.y)*(A[a].b.x-A[b].a.x);
return h*i<=eps&&j*k<=eps;
}
void getinter(point p1,point p2,point p3,point p4,point &inter){
inter=p1;
double ans=((p1.x-p3.x)*(p3.y-p4.y)-(p1.y-p3.y)*(p3.x-p4.x))/((p1.x-p2.x)*(p3.y-p4.y)-(p1.y-p2.y)*(p3.x-p4.x));
inter.x+=(p2.x-p1.x)*ans;
inter.y+=(p2.y-p1.y)*ans;
}
int main()
{
int t,i,j,k;
scanf("%d",&t);
while(t--){
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&A[0].a.x,&A[0].a.y,&A[0].b.x,&A[0].b.y,&A[1].a.x,&A[1].a.y,&A[1].b.x,&A[1].b.y);
if(A[0].a.x==A[1].a.x&&A[0].a.y==A[1].a.y){
printf("yes %.lf %.1f",A[0].a.x,A[0].a.y);
}
else if(A[0].a.x==A[1].b.x&&A[0].a.y==A[1].b.y){
printf("yes %.1f %.1f\n",A[0].a.x,A[0].a.y);
}
else if(A[0].b.x==A[1].a.x&&A[0].b.y==A[1].a.y){
printf("yes %.1f %.1f\n",A[0].b.x,A[0].b.y);
}
else if(A[0].b.x==A[1].b.x&&A[0].b.y==A[1].b.y){
printf("yes %.1f %.1f\n",A[0].b.x,A[0].b.y);
}
else if(judge(0,1)){
point inter;
getinter(A[0].a,A[0].b,A[1].a,A[1].b,inter);
printf("yes %.1f %.1f\n",inter.x,inter.y);
}
else
printf("no\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nyoj1132promise me a