[백준]다각형의 면적 with Java

hyeok ryu·2024년 3월 9일
0

algorithm

목록 보기
8/8

문제

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


입력

첫째 줄에 N이 주어진다.
다음 N개의 줄에는 다각형을 이루는 순서대로 N개의 점의 x, y좌표가 주어진다.


출력

첫째 줄에 면적을 출력한다.
면적을 출력할 때에는 소수점 아래 둘째 자리에서 반올림하여 첫째 자리까지 출력한다.


풀이

제한조건

  • 좌표값은 절댓값이 100,000을 넘지 않는 정수이다.

접근방법

수학

고등학교 시절, 수학시간을 떠올려보자.
다각형의 좌표 정보를 기반으로 하여, 서로 교차하여 곱하여 다각형의 면적을 구할 수 있는 공식이 있다.

https://namu.wiki/w/%EC%8B%A0%EB%B0%9C%EB%81%88%20%EA%B3%B5%EC%8B%9D

만약 문제의 좌표들이 뒤죽박죽이라면, 해당 공식을 바로 적용하기에는 부적합하나, 문제에서는
순서대로 좌표를 제공한다.
따라서 공식에 맞게 순서대로 계산만 하면된다.

주의할 점
타입 캐스팅에 주의하자.
문제의 입력은 최대 10만으로, 곱셉을 할 경우 수가 상당히 커진다.
이때, 자료형에 따라 오버플로, 타입 캐스팅의 문제가 발생할 수 있다.
주의하자.


코드

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {
	static int N;

	static class Point {
		int x;
		int y;

		Point(int a, int b) {
			x = a;
			y = b;
		}
	}

	public static void main(String[] args) throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		N = stoi(in.readLine());
		List<Point> list = new ArrayList<>();
		for (int i = 0; i < N; ++i) {
			String[] inputs = in.readLine().split(" ");
			list.add(new Point(stoi(inputs[0]), stoi(inputs[1])));
		}

		int size = list.size() - 1;
		double res1 = (double)list.get(size).x * (double)list.get(0).y;
		double res2 = (double)list.get(0).x * (double)list.get(size).y;
		for (int i = 0; i < size; ++i) {
			res1 += (double)list.get(i).x * (double)list.get(i + 1).y;
			res2 += (double)list.get(i + 1).x * (double)list.get(i).y;
		}

		double result = Math.abs(res1 - res2) * 0.5;
		result *= 10;
		Math.round(result);
		result *= 0.1;

		System.out.printf("%.1f", result);
	}

	public static int stoi(String s) {
		return Integer.parseInt(s);
	}
}

0개의 댓글