點與多多邊形的關係

問題

點的位置


二維平面上會給出以N個點構成的多邊形。

當平面上面給出點 P1, P2時,請編寫出判斷點 P1, P2是否在多邊形外部,或者是在內部的程序。

P1, P2 不會在多邊形的邊上面。

輸入


第一行給出構成多邊形的個數(1N100,000)


第二行開始給出將輸入的N個點的整數座標(-10^9 x, y 10^9)


多邊形的座標按順時針方向或逆時針方向給出。


最後兩行給出點 P1, P2 的座標。


輸出


第一行上,如果點 P1在多邊形裏面的話,輸出"in",在外邊的話,輸出"out"


第二行上,如果點 P2在多邊形裏面的話,輸出"in", 在外邊的話,輸出"out"


 


輸入案例


4

1 1

1 3

3 3

3 1

0 0

2 2


輸出案例


out

in


 



#include <cstdio>
#include <vector>
#define maxfunc(a,b)(a>b?a:b)
#define minfunc(a,b)(a<b?a:b)

using namespace std;

typedef struct point{
	long x, y;
}Point;

typedef struct poligon{
	int ptNums;
	Point *ptlst;
}Poligon;
int n,cas;
int main(){
	vector<Point> vpt;
	vpt.reserve(100001);
	scanf("%d", &n);
	for (int i = 0; i < n; i++){
		Point p;
		
		scanf("%ld%ld", &p.x, &p.y);
	
		vpt.push_back(p);
	}
	Poligon pol;
	pol.ptNums = n;
	pol.ptlst = &vpt[0];

	Point testpt;
	cas = 0;
	while (scanf("%ld%ld", &testpt.x, &testpt.y) == 2)
	{
		int cnt = 0;
		for (int i = 0; i < pol.ptNums; i++){
			long x1, x2, y1, y2;
			double tx, t;
			x1 = pol.ptlst->x, y1 = pol.ptlst->y;
			
			if (i == (n - 1)){
				// next point is first point(0) if current is n-1
				pol.ptlst -= (n - 1);
			}
			else pol.ptlst++; // go next point 
			x2 = pol.ptlst->x, y2 = pol.ptlst->y;
			//tmp1 = maxfunc(y1, y2);

			if (testpt.y >= maxfunc(y1, y2) || testpt.y <= minfunc(y1, y2)) continue;
			t = (double)(testpt.y - y2) / (y1 - y2);
			// tx is the cross point
			tx = (double)x2 - t*(x2 - x1);
			// only count the point at left of tx
			if (testpt.x < tx) cnt++;
		}
		printf("%s\n", cnt % 2 == 0 ? "out" : "in");
		if(++cas>1) break;
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章