每日一题之 hiho225周 Inside Triangle

描述
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值