每日一题之 hiho225周 Inside Triangle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014046022/article/details/83270961

描述
Determine if a point is inside a 2D triangle.

输入
The first line contains an integer T denoting the number of test case. (1 <= T <= 10)

The following T lines each contain 8 integers, Px, Py, Ax, Ay, Bx, By, Cx, Cy. P denotes the point. ABC denotes the triangle. The coordinates are within [-1000000, 1000000].

输出
For each test case output YES or NO denoting if the point is inside the triangle. Note that the point is considered inside the triangle if the point is just on some side of the triangle.

样例输入
2
0 1 -1 0 1 0 0 2
0 0 0 1 1 0 1 1
样例输出
YES
NO

题意:

给一个点 P, 以及三角形的三个顶点 A,B, C 判断 P 是否在三角形内。

思路:

可以直接用面积法来判断, 如果P 在三角形内,那么以P为顶点的三个小三角形的面积和大的三角形ABC相等。否则不等。 不过还需要注意的是精度问题,坐标范围算线段长度的时候会爆int,然后算平方根的时候会有精度损失。最后将eps设置为0.1才过!!!

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

double eps = 0.1;

typedef long double ll;

ll cal(ll ax, ll ay, ll bx, ll by) {

	ll res = (ax-bx)*(ax-bx) + (ay-by)*(ay-by);

	return res;
}

ll area(ll ax, ll ay, ll bx, ll by, ll cx, ll cy) {

	ll ab = sqrt(cal(ax, ay, bx, by));
	ll ac = sqrt(cal(ax, ay, cx, cy));
	ll bc = sqrt(cal(bx, by, cx, cy));

	ll p = (ab+bc+ac)/2;
	ll tmp = p*(p-ac)*(p-bc)*(p-ab);
	ll res = sqrt(tmp);

	return res;
}

void solve(vector<ll>&X, vector<ll>&Y) {

	ll S  = area(X[1], Y[1], X[2], Y[2], X[3], Y[3]);

	ll s1 = area(X[0], Y[0], X[1], Y[1], X[2], Y[2]);
	ll s2 = area(X[0], Y[0], X[1], Y[1], X[3], Y[3]);
	ll s3 = area(X[0], Y[0], X[2], Y[2], X[3], Y[3]);

	ll S1 = s1+s2+s3;

	if (fabs(S - S1) <= eps) {
		cout << "YES" << endl;
	}
	else 
		cout << "NO" << endl;
}

int main() {

	int t,x,y;
	cin >> t;
	vector<ll>X;
	vector<ll>Y;
	while(t--) {
		X.clear();
		Y.clear();
		for (int i = 0; i < 4; ++i) {
			cin >> x >> y;
			X.push_back(x);
			Y.push_back(y);
		}
		solve(X,Y);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/83270961
今日推荐