点的位置---简单的解析几何

题目链接 点的位置

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class source
{
public static void main(String[] args) throws IOException
{
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
final int N = Integer.parseInt(st.nextToken());
final int[][] point = new int[N + 1][2];
for (int i = 0; i < N; i++)
{
st = new StringTokenizer(br.readLine());
point[i][0] = Integer.parseInt(st.nextToken());
point[i][1] = Integer.parseInt(st.nextToken());
}

point[N] = point[0];

final int[] tp1 = new int[2];
final int[] tp2 = new int[2];

st = new StringTokenizer(br.readLine());
tp1[0] = Integer.parseInt(st.nextToken());
tp1[1] = Integer.parseInt(st.nextToken());

st = new StringTokenizer(br.readLine());
tp2[0] = Integer.parseInt(st.nextToken());
tp2[1] = Integer.parseInt(st.nextToken());

final boolean tp1In = isInSide(point, tp1);
final boolean tp2In = isInSide(point, tp2);

if (tp1In)
{
System.out.println("in");
} else
{
System.out.println("out");
}
if (tp2In)
{
System.out.println("in");
} else
{
System.out.println("out");
}

}

private static boolean isInSide(int[][] graph, int[] target)
{
int crossCnt = 0;
final int length = graph.length;
int x0 = target[0];
int y0 = target[1];
for (int i = 1; i < length; i++)
{
if (Arrays.equals(graph[i], target))
{
return false;
}
double x1 = graph[i-1][0];
double y1 = graph[i-1][1];
double x2 = graph[i][0];
double y2 = graph[i][1];
if((y1<y0&&y2>=y0) ||(y1>=y0&&y2<y0)){ double crossx = 0; if(x1 == x2){ crossx = x1; } else{ crossx = ((x2-x1)/(y2-y1))*y0 + (x1*y2-y1*x2)/(y2-y1); } if(crossx>x0){
crossCnt++;
}
}
}
return crossCnt % 2 != 0;
}
}

posted @ 2021-04-30 15:30  Monstro  阅读(116)  评论(0)    收藏  举报