๊ธฐ๋ก๋ฐฉ

BOJ_2166 : ๋‹ค๊ฐํ˜•์˜ ๋ฉด์  ๋ณธ๋ฌธ

CodingTest/Java

BOJ_2166 : ๋‹ค๊ฐํ˜•์˜ ๋ฉด์ 

Soom_1n 2024. 3. 11. 16:17

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

2166๋ฒˆ: ๋‹ค๊ฐํ˜•์˜ ๋ฉด์ 

์ฒซ์งธ ์ค„์— N์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๋‹ค๊ฐํ˜•์„ ์ด๋ฃจ๋Š” ์ˆœ์„œ๋Œ€๋กœ N๊ฐœ์˜ ์ ์˜ x, y์ขŒํ‘œ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ขŒํ‘œ๊ฐ’์€ ์ ˆ๋Œ“๊ฐ’์ด 100,000์„ ๋„˜์ง€ ์•Š๋Š” ์ •์ˆ˜์ด๋‹ค.

www.acmicpc.net


๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • N๊ฐœ์˜ ๊ผญ์ง€์ ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹ค๊ฐํ˜•์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.
  • ๋‹ค๊ฐํ˜•์˜ ๋„“์ด(๋ฉด์ )์„ ์†Œ์ˆ˜์  ๋‘˜์งธ ์ž๋ฆฌ์—์„œ ๋ฐ˜์˜ฌ๋ฆผํ•˜์—ฌ ์ฒซ์งธ ์ž๋ฆฌ๊นŒ์ง€ ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ ๋ฌธ์ œ ํ’€์ด ๐Ÿ”ธ

  • ์‹ ๋ฐœ๋ˆ ๊ณต์‹ (Shoelace formula)์˜ ์ „ํ˜•์ ์ธ ์—ฐ์Šต ๋ฌธ์ œ์ด๋‹ค.
  • x์ขŒํ‘œ์™€ y์ขŒํ‘œ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๊ณต์‹์„ ๊ตฌํ˜„ํ•˜๊ณ , ์†Œ์ˆ˜์  ์ฒซ์งธ ์ž๋ฆฌ๊นŒ์ง€ ๋ฐ˜์˜ฌ๋ฆผํ•ด ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

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));

        int N = Integer.parseInt(br.readLine());
        long[] X = new long[N];
        long[] Y = new long[N];

        StringTokenizer st = null;
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            X[i] = Long.parseLong(st.nextToken());
            Y[i] = Long.parseLong(st.nextToken());
        }

        double sum = X[N - 1] * Y[0] - Y[N - 1] * X[0];
        for (int i = 0; i < N - 1; i++) {
            sum += X[i] * Y[i + 1];
            sum -= Y[i] * X[i + 1];
        }

        sum = Math.round((Math.abs(sum) / 2.0) * 10.0) / 10.0;

        bw.write(String.format("%.1f", sum));
        bw.flush();
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • ์ขŒํ‘œ๋ฅผ long๋ฐฐ์—ด x์™€ y์— ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.
    • ์ขŒํ‘œ๊ฐ’์ด ์ตœ๋Œ€ 10๋งŒ์ด๋ฏ€๋กœ, ์‹ ๋ฐœ๋ˆ ๊ณต์‹ ์ ์šฉ ๋ถ€๋ถ„์—์„œ ๊ณฑ์…ˆํ•  ๋•Œ ์˜ค๋ฒ„ํ”Œ๋กœ๊ฐ€ ๋‚  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ long์œผ๋กœ ์„ ์–ธํ•œ๋‹ค.
  • ์ขŒํ‘œ๊ฐ’์ด ๋ˆ„์ ๋˜๋Š” ๋ณ€์ˆ˜ sum์€ ์†Œ์ˆ˜์  ๊ณ„์‚ฐ๋„ ํ•„์š”ํ•˜๊ณ , ๊ฐ’์ด ์ปค์งˆ ์ˆ˜ ์ž‡์œผ๋ฏ€๋กœ double๋กœ ์„ ์–ธํ•œ๋‹ค.
    • ์ ˆ๋Œ€๊ฐ’ ๋ฐ ์†Œ์ˆ˜์  ๊ณ„์‚ฐ์—์„œ ์†Œ์ˆ˜์  ๊ณ„์‚ฐ์ด ํ‹€๋ฆฌ์ง€ ์•Š๋„๋ก 2.0, 10.0 ๊ฐ™์€ ์‹ค์ˆ˜๋กœ ๊ณ„์‚ฐํ•œ๋‹ค.
  • ์†Œ์ˆ˜์  1์˜์ž๋ฆฌ ์ˆ˜๊นŒ์ง€ String.format์„ ์ด์šฉํ•ด ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์‹ ๋ฐœ๋ˆ ๊ณต์‹์„ ๋ชฐ๋ผ์„œ ํ’€ ์ˆ˜ ์—†์—ˆ๋˜ ๋ฌธ์ œ์˜€๋‹ค.
    • ์งˆ๋ฌธ ๊ฒŒ์‹œํŒ์„ ๋ณด๊ณ , ์ด ๊ณต์‹์ด ํ•„์ˆ˜๊ตฌ๋‚˜ ํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•ด์„œ ๋จผ์ € ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ •๋ฆฌํ•œ ํ›„ ํ’€์—ˆ๋‹ค.
  • ์ขŒํ‘œ๋ฅผ int๋กœ ๋ฐ›์•„์„œ ์˜ค๋ฒ„ํ”Œ๋กœ๊ฐ€ ๋‚˜๊ฑฐ๋‚˜, ์‹ค์ˆ˜๋Œ€์‹  ์ •์ˆ˜๋กœ ๊ณ„์‚ฐํ•ด์„œ ์ •ํ™•๋„์—์„œ 2๋ฒˆ ํ‹€๋ ธ์—ˆ๋‹ค.

728x90