Points Within
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 24 Accepted Submission(s) : 7
You're expected to write a program which tells us if a given point lies inside a given polygon described by the coordinates of its vertices. You can assume that if a point is in the border of the polygon, then it is in fact inside the polygon.
Input Format
The input file may contain several instances of the problem. Each instance consists of: (i) one line containing integers N, 0 < N < 100 and M, respectively the number of vertices of the polygon and the number of points to be tested. (ii) N lines, each containing a pair of integers describing the coordinates of the polygon's vertices; (iii) M lines, each containing a pair of integer coordinates of the points which will be tested for "withinness" in the polygon.
You may assume that: the vertices are all distinct; consecutive vertices in the input are adjacent in the polygon; the last vertex is adjacent to the first one; and the resulting polygon is simple, that is, every vertex is incident with exactly two edges and two edges only intersect at their common endpoint. The last instance is followed by a line with a 0 (zero).
Output Format
For the ith instance in the input, you have to write one line in the output with the phrase "Problem i:", followed by several lines, one for each point tested, in the order they appear in the input. Each of these lines should read "Within" or "Outside", depending on the outcome of the test. The output of two consecutive instances should be separated by a blank line.
Sample Input
3 1
0 0
0 5
5 0
10 2
3 2
4 4
3 1
1 2
1 3
2 2
0
Sample Output
Problem 1:
Outside
Problem 2:
Outside
Within
这道题目实际上用到的是判断点在多边形内部的情况,实际上用到的是可以用到假设一条过测试点平行于x轴的射线,方向向右,
统计多边形穿过这条射线正反多少次,把这个书记为绕数sum,逆时针穿过时,sum++
顺时针穿过时 sum--;
代码如下:::
》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》
#include <iostream>
#include <cstdio>
using namespace std;
int flag=0;//标记交于顶点的个数
const int maxn=200;
struct node
{
int x,y;
};
node a[maxn];
int n,m;
int inl(node d,node c,node e)
{
int x1=c.x-d.x;
int y1=c.y-d.y;
int x2=e.x-d.x;
int y2=e.y-d.y;
return x1*x2+y1*y2;
}
int cross(node d,node c,node e)
{
int x1=d.x-c.x;
int y1=d.y-c.y;
int x2=e.x-c.x;
int y2=e.y-c.y;
return x2*y1-x1*y2;
}
int just(node b)
{
int sum=0;
for(int j=0;j<n;j++)
{
int d=cross(b,a[j],a[(j+1)%n]);
if(d==0)//在边上
{
if(0>=inl(b,a[j],a[(j+1)%n]))//在线端上
return 1;
}
int d1=a[j].y-b.y;
int d2=a[(j+1)%n].y-b.y;
if(d>0&&d1<=0&&d2>0)
sum++;
if(d<0&&d2<=0&&d1>0)
sum--;
}
if(sum!=0)
return 1;//在内边
else
return 0;
}
int main()
{
int k=0;
node b;
while(scanf("%d",&n)!=EOF&&n)
{
scanf("%d",&m);
if(k!=0)
printf("\n");
for(int i=0;i<n;i++)
scanf("%d %d",&a[i].x,&a[i].y);
printf("Problem %d:\n",++k);
for(int i=0;i<m;i++)
{
scanf("%d %d",&b.x,&b.y);
if(just(b))
printf("Within\n");
else
printf("Outside\n");
}
}
return 0;
}
/**
6 1
1 0
2 1
2 4
1 5
0 3
0 1
**/