TZOJ 3005 Triangle(判断点是否在三角形内+卡精度)
描述
Given the coordinates of the vertices of a triangle,And a point. You just need to judge whether the point is in the Triangle.
输入
The input contains several test cases. For each test case, only line contains eight integer numbers , describing the coordinates of the triangle and the point. All the integer is in range of [-100 , 100].
The end of the input is indicated by a line containing eight zeros separated by spaces.
输出
For each test case , if the point is inside of the triangle ,please output the string ”YES”, else output the string “NO”. You just need to follow the following examples.
样例输入
0 0 4 0 0 4 3 1
0 0 4 0 0 4 1 2
0 0 4 0 0 4 -1 -1
0 0 0 0 0 0 0 0
样例输出
NO
YES
NO
思路:
通过判断3个小三角形面积是否等于大三角形面积即可,这道题卡精度,要控制误差在1e-9。
#include<bits/stdc++.h> using namespace std; struct node{ int x,y; }a,b,c,p; double edge(int x1,int y1,int x2,int y2) { return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } double area(int x1,int y1,int x2,int y2,int x3,int y3) { double A=edge(x1,y1,x2,y2); double B=edge(x1,y1,x3,y3); double C=edge(x3,y3,x2,y2); double L=(A+B+C)*1.0/2; return fabs(sqrt(L*(L-A)*(L-B)*(L-C))); } bool check(double a,double b,double c,double p) { if(a==0||b==0||c==0) return false; if(fabs(a+b+c-p)<=1e-9) return true; return false; } int main() { while(cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y>>p.x>>p.y,a.x||a.y||b.x||b.y||c.x||c.y||p.x||p.y) { double s=area(a.x,a.y,b.x,b.y,c.x,c.y); double abp=area(a.x,a.y,b.x,b.y,p.x,p.y); double acp=area(a.x,a.y,c.x,c.y,p.x,p.y); double bcp=area(c.x,c.y,b.x,b.y,p.x,p.y); if(check(abp,acp,bcp,s)) printf("YES\n"); else printf("NO\n"); } return 0; }