728x90
코드
package Baekjoon.Class;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class P_2166 {
static int n;
static ArrayList<Point> points;
static class Point {
long x, y;
public Point(long x, long y) {
this.x = x;
this.y = y;
}
public Point(Point point) {
this.x = point.x;
this.y = point.y;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
points = new ArrayList<>();
for (int i = 0; i < n; i++) {
long[] line = Arrays.stream(br.readLine().split(" ")).mapToLong(Long::parseLong).toArray();
points.add(new Point(line[0], line[1]));
}
points.add(new Point(points.get(0)));
System.out.println(String.format("%.1f", shoelace()));
br.close();
}
private static double shoelace() {
long sum1 = 0l, sum2 = 0l;
for (int i = 0; i < n; i++) {
sum1 += points.get(i).x * points.get(i + 1).y;
sum2 += points.get(i + 1).x * points.get(i).y;
}
return Math.abs(sum1 - sum2) * 0.5;
}
}
코드 설명
신발끈 공식을 사용해서 다각형의 면적을 구했다.
신발끈 공식 - 나무위키
우선 이 공식을 유도하기 전 꼭짓점이 A(x1, y1){\rm A}(x_{1},\,y_{1})A(x1,y1), B(x2, y2){\rm B}(x_{2},\,y_{2})B(x2,y2), C(x3, y3){\rm C}(x_{3},\,y_{3})C(x3,y3)인 삼각형의 넓이를 구하는 방법을 고찰해볼
namu.wiki
공식을 알고 있음에도 엄청 틀렸는데 long과 관련된 문제였다.
입력도 long으로 받아야 성공이던데 이건 문제에서 '좌표값은 절댓값이 100,000을 넘지 않는 정수' 라고 했는데 왜 long으로 해야하는지 모르겠다
신발끈 공식을 사용할 때에도 한 변수에 결과값을 모두 담으면 안된다.반올림도 Math.round(ans * 10 / 10.0)을 했는데 double로 넘어가는 순간 * 10을 할 때 오버플로우가 발생할 수 있다
728x90
'코딩테스트 > 백준' 카테고리의 다른 글
P.27172 수 나누기 게임 (0) | 2023.08.15 |
---|---|
P.2467 용액 (0) | 2023.08.15 |
P.11779 최소비용 구하기 2 (0) | 2023.08.13 |
P.1865 웜홀 [추가] (0) | 2023.08.12 |
P.1238 파티 (0) | 2023.08.09 |