/************************************************************************* > File Name: poj_1584_back.cpp > Author: Howe_Young > Mail: [email protected] > Created Time: 2015年04月06日 星期一 19时03分03秒 ************************************************************************/ #include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <cstdio> #define EPS 1e-8 using namespace std; struct point{ double x, y; }; const int N = 1000; point p[N]; int sgn(double d) { if (fabs(d) < EPS) return 0; return d > 0 ? 1 : -1; } double x_mutli(point p1, point p2) { return (p1.x * p2.y - p2.x * p1.y); } double dot_multi(point p1, point p2) { return (p1.x * p2.x + p1.y * p2.y); } //方向 double get_direction(point p1, point p2, point p3) { point v1, v2; v1.x = p3.x - p1.x; v1.y = p3.y - p1.y; v2.x = p2.x - p1.x; v2.y = p2.y - p1.y; return x_mutli(v1, v2); } //得到模长 double get_length_of_mold(point p) { return sqrt(p.x * p.x + p.y * p.y); } bool is_vonvex(int n) { double tmp1 = 0.0, tmp2; for (int i = 0; i < n; i++)//因为凸多边形的相邻边的拐向都相同,要么都顺时针,要么多逆时针 { tmp2 = sgn(get_direction(p[i], p[(i+1)%n], p[(i+2)%n])); if (tmp1 * tmp2 < -EPS) return false; tmp1 = tmp2; } return true; } //叉积判断点是否在多边形内,只适合凸多边形 bool point_in_polygon(point peg, int n) { double tmp1 = 0.0, tmp2; for (int i = 0; i < n; i++) { tmp2 = sgn(get_direction(p[i], p[(i+1)%n], peg)); if (tmp1 * tmp2 < -EPS) return false; tmp1 = tmp2; } return true; } //判断圆是否在多边形内,就是判断点到边的最小离跟半径的关系 bool circle_in_polygon(point peg, double peg_r, int n) { if (peg_r == 0.0) return true; double shadow;//v1向量在v2向量上的投影长度 a点乘b然后除以b的模就是a在b上的投影 point v1, v2; double ans; for (int i = 0; i < n; i++) { v1.x = peg.x - p[i].x; v1.y = peg.y - p[i].y; v2.x = p[(i+1)%n].x - p[i].x; v2.y = p[(i+1)%n].y - p[i].y; shadow = dot_multi(v1, v2) / (v2.x * v2.x + v2.y * v2.y) * 1.0;//这里是求投影占v2向量模的长度 的比例,如果大于1,或者小于0, 垂足肯定在外面了 if (shadow >= 0.0 && shadow <= 1.0)//利用面积来求高,也就是距离,叉乘的绝对值是三角形面积的两倍 ans = fabs(x_mutli(v1, v2)) / get_length_of_mold(v2); else { //如果垂足在外面,找最近的一个端点 v2.x = peg.x - p[(i+1)%n].x; v2.y = peg.y - p[(i+1)%n].y; ans = sgn(get_length_of_mold(v1) - get_length_of_mold(v2)) == -1 ? get_length_of_mold(v1) : get_length_of_mold(v2); } if (ans - peg_r < -EPS)//如果相交,返回false return false; } return true; } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n; point peg; double peg_r; while (~scanf("%d", &n) && n >= 3) { scanf("%lf %lf %lf", &peg_r, &peg.x, &peg.y); for (int i = 0; i < n; i++) scanf("%lf %lf", &p[i].x, &p[i].y); if (!is_vonvex(n))//判断是否是凸多边形 { puts("HOLE IS ILL-FORMED"); continue; } if (point_in_polygon(peg , n) && circle_in_polygon(peg, peg_r, n)) { puts("PEG WILL FIT"); } else puts("PEG WILL NOT FIT"); } return 0; }
时间: 2024-10-13 02:59:37