[백준(Baekjoon)][자바(java)] 6487 : 두 직선의 교차 여부 / 기하

728x90

 

https://www.acmicpc.net/problem/6487

 

6487번: 두 직선의 교차 여부

두 개의 직선을 나타내는 4개의 점이 입력으로 주어질 때, 두 직선이 만나는지를 확인하는 프로그램을 작성하시오.

www.acmicpc.net

 

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

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine()), x1, y1, x2, y2, x3, y3, x4, y4, a, b, c, d, e, f; double ad_bc, r;
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		while (n-- > 0) {
			st = new StringTokenizer(br.readLine());
			x1 = Integer.parseInt(st.nextToken()); y1 = Integer.parseInt(st.nextToken());
			x2 = Integer.parseInt(st.nextToken()); y2 = Integer.parseInt(st.nextToken());
			x3 = Integer.parseInt(st.nextToken()); y3 = Integer.parseInt(st.nextToken());
			x4 = Integer.parseInt(st.nextToken()); y4 = Integer.parseInt(st.nextToken());
			a = x2 - x1; b = y2 - y1; c = x4 - x3; d = y4 - y3;
			e = x3 - x1; f = y3 - y1; ad_bc = a * d - b * c;
			if (ad_bc != 0) {
				r = (d * e - c * f) / ad_bc;
				sb.append(String.format("POINT %.2f %.2f", a * r + x1, b * r + y1));
			}
			else sb.append(e * b - f * a == 0 ? "LINE" : "NONE");
			sb.append("\n");
		}
		br.close();
		System.out.print(sb.toString());
	}
}
public class Main {
	
	public static String isIntersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
		int a, b, c, d, e, f; double ad_bc, r;
		a = x2 - x1; b = y2 - y1; c = x4 - x3; d = y4 - y3;
		e = x3 - x1; f = y3 - y1; ad_bc = a * d - b * c;
		if (ad_bc != 0) {
			r = (d * e - c * f) / ad_bc;
			return String.format("POINT %.2f %.2f", a * r + x1, b * r + y1);
		}
		else return e * b - f * a == 0 ? "LINE" : "NONE";
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine()), xy[][] = new int[4][2], i ,j;
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		while (n-- > 0) {
			st = new StringTokenizer(br.readLine());
			for (i = 0; i < 4; ++i)
				for (j = 0; j < 2; ++j)
					xy[i][j] = Integer.parseInt(st.nextToken());
			sb.append(isIntersect(xy[0][0], xy[0][1], xy[1][0], xy[1][1], xy[2][0], xy[2][1], xy[3][0], xy[3][1]) + "\n");
		}
		br.close();
		System.out.print(sb.toString());
	}
}

 

 

반응형