[백준] 11785 - CCW (java)

HaYeong Jang·2021년 1월 13일
0

[백준] 알고리즘

목록 보기
1/62
post-thumbnail

문제

2차원 좌표 평면 위에 있는 점 3개 P1, P2, P3가 주어진다. P1, P2, P3를 순서대로 이은 선분이 어떤 방향을 이루고 있는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 P1의 (x1, y1), 둘째 줄에 P2의 (x2, y2), 셋째 줄에 P3의 (x3, y3)가 주어진다. (-10,000 ≤ x1, y1, x2, y2, x3, y3 ≤ 10,000) 모든 좌표는 정수이다. P1, P2, P3의 좌표는 서로 다르다.

출력

P1, P2, P3를 순서대로 이은 선분이 반시계 방향을 나타내면 1, 시계 방향이면 -1, 일직선이면 0을 출력한다.

예제 입력

1 1
5 5
7 3

예제 출력

-1

코드

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());

        // P1
        int x1 = Integer.parseInt(st.nextToken());
        int y1 = Integer.parseInt(st.nextToken());

        // P2
        st = new StringTokenizer(br.readLine());
        int x2 = Integer.parseInt(st.nextToken());
        int y2 = Integer.parseInt(st.nextToken());

        // P3
        st = new StringTokenizer(br.readLine());
        int x3 = Integer.parseInt(st.nextToken());
        int y3 = Integer.parseInt(st.nextToken());

        int ccw = (x1 * y2 + x2 * y3 + x3 * y1) - (y1 * x2 + y2 * x3 + y3 * x1);
        if (ccw > 0) {  // 반시계 방향
            bw.write(1 + "\n");
        } else if (ccw < 0) {   // 시계 방향
            bw.write(-1 + "\n");
        } else {  // 일직선인 경우
            bw.write(0 + "\n");
        }

        br.close();
        bw.flush();
        bw.close();
    }
}

정리

  • 신발끈 공식을 알고 있어야 했다.
  • 세 점의 좌표가 주어질 때, (x1y2+x2y3+x3y1) - (y1x2+y2x3+y3x1)
    양수이면 CCW, 음수이면 CW, 0이면 일직선이다.
profile
기억하기 위해 기록하는 개발로그👣

0개의 댓글