Design a site like this with WordPress.com
Get started

Xét vị trí tương đối của 1 điểm với 1 tam giác

package practice;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/*
* cho 1 tam giác ABC có tọa độ 3 đỉnh: x1,y1,x2,y2,x3,y3
* và điểm P(x,y)
* xác định xem đỉnh P:
* 1. nằm trong tam giác
* 2. nằm trên cạnh của tam giác
* 3. nằm ngoài tam giác
*
* Ý tưởng: làm theo diện tích tam giác vs công thức trong hệ tọa độ oxy
* dt tam giác ABC = |(x1*(y2-y3)-x2*(y1-y3)+x3*(y1-y2))|/2
*
* Lưu ý: đó là nếu làm vs kiểu dữ liệu double thì ko chính xác bằng float được
* float chính xác gấp đôi double, chịu được tải cũng gấp đôi luôn
*/
public class TamGiac {
Scanner sc = new Scanner(System.in);

float triTuyetDoi(float a) {
if (a >= 0.0)
return a;
return -a;
}

float dienTich(int x1, int y1, int x2, int y2, int x3, int y3) {
return triTuyetDoi(x1 * (y2 – y3) – x2 * (y1 – y3) + x3 * (y1 – y2)) / 2;
}

void solve(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y) {
float dtABC = dienTich(x1, y1, x2, y2, x3, y3);
float dtABP = dienTich(x1, y1, x2, y2, x, y);
float dtACP = dienTich(x1, y1, x, y, x3, y3);
float dtBCP = dienTich(x, y, x2, y2, x3, y3);
if (dtABP == 0 || dtACP == 0 || dtBCP == 0)
System.out.println(2);
else if ((dtABP + dtACP + dtBCP) == dtABC)
System.out.println(1);
else
System.out.println(3);
}

void solution() {
int t, x1, y1, x2, y2, x3, y3, x, y;
t = sc.nextInt();
for (int tc = 1; tc <= t; tc++) {
x1 = sc.nextInt();
y1 = sc.nextInt();
x2 = sc.nextInt();
y2 = sc.nextInt();
x3 = sc.nextInt();
y3 = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
solve(x1, y1, x2, y2, x3, y3, x, y);
}
}

public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream(“TamGiac.txt”));
TamGiac t = new TamGiac();
t.solution();
}

}

Advertisement

Author: alexishuuuocn

I'm a software engineer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: