Algorithm/BOJ(Baekjoon Online Judge)

[백준 - 11758번] CCW - Java //Wello Horld//

koucop 2019. 8. 6. 14:23

이번에는 BOJ의 11758번 문제 "CCW"를 풀어보도록 하자.

이차원(2D)에서 차례대로 주어지는 세점의 회전방향 (CW(Clockwise, 시계 방향), CCW(Counter-Clockwise, 반시계 방향)) 을 결정하기 위해서는, 세점의 좌표가 (x1, y1), (x2, y2), (x3,y3)와 같이 주어졌다 할 때, 신발끈 공식을 이용해서 세점이 CW인지 CCW인지 간단하게 구할 수 있다. 신발끈 공식을 통해서 해당 값이 0보다 크면 반시계 방향, 0보다 작으면 시계 방향, 0과 같으면 일직선이 된다.

성공한 코드는 아래와 같다.

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

public class sample {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        StringTokenizer st = new StringTokenizer(br.readLine());
        Point p1 = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
        st = new StringTokenizer(br.readLine());
        Point p2 = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
        st = new StringTokenizer(br.readLine());
        Point p3 = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
        bw.write(ccw(p1, p2, p3) + "\n");

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

    public static int ccw(Point a, Point b, Point c){
        int result = a.x * b.y + b.x * c.y + c.x * a.y - (a.y * b.x + b.y * c.x + c.y * a.x);
        if(result > 0) return 1;
        else if(result < 0) return -1;
        else return 0;
    }

    public static class Point{
        int x, y;
        public Point(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
}

 

문제 : https://www.acmicpc.net/problem/11758

 

11758번: CCW

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

www.acmicpc.net