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
풀이
더보기
벡터의 외적을 이용하여 구하는 방식이다.
점 3개가 주어졌을 때 벡터의 외적을 구해서 외적 값이 0보다 크면 반시계 0이면 일직선 0보다 작으면 시계 방향으로 계산한다.
x1 x2 x3
\ \
y1 y2 y3
x1 x2 x3
/ /
y1 y2 y3
즉 (x1*y2 + x2*y3 + x3*y1) - (x2y1 + x3y2+x1y3) 값을 비교한다.
코드
package test11758;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
MyScanner sc = new MyScanner(System.in);
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
int x3 = sc.nextInt();
int y3 = sc.nextInt();
System.out.println(ccw(x1, y1, x2, y2, x3, y3));
sc.close();
}
static int ccw(int x1, int y1, int x2, int y2, int x3, int y3) {
// 벡터 외적
int temp = (x1 * y2 + x2 * y3 + x3 * y1) - (y1 * x2 + y2 * x3 + y3 * x1);
if (temp > 0) {
return 1; // 반시계
} else if (temp < 0) {
return -1; // 시계
} else {
return 0; // 일직선
}
}
static class MyScanner {
final BufferedReader reader;
final BufferedWriter writer;
static StringTokenizer tokenizer = null;
MyScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
writer = new BufferedWriter(new OutputStreamWriter(System.out));
}
String nextToken() throws IOException {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
void write(String sb) throws IOException {
writer.write(sb);
}
void close() throws IOException {
reader.close();
writer.close();
}
}
}
참고
ccw 알고리즘: https://snowfleur.tistory.com/98
'Algorithms > 2023 Pro 시험 준비' 카테고리의 다른 글
3691 컴퓨터조립 - 백준 (0) | 2023.08.21 |
---|---|
2166 다각형의 면적 - 백준 (0) | 2023.08.16 |
2957 이진 탐색 트리 - 백준 (0) | 2023.08.08 |
2613 숫자구슬 - 백준 (0) | 2023.08.08 |
1761 정점들의 거리 - 백준 (0) | 2023.08.01 |