๊ธฐ๋ก๋ฐฉ

BOJ_1715 : ์นด๋“œ ์ •๋ ฌํ•˜๊ธฐ ๋ณธ๋ฌธ

CodingTest/Java

BOJ_1715 : ์นด๋“œ ์ •๋ ฌํ•˜๊ธฐ

Soom_1n 2024. 2. 11. 20:41

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

 

1715๋ฒˆ: ์นด๋“œ ์ •๋ ฌํ•˜๊ธฐ

์ •๋ ฌ๋œ ๋‘ ๋ฌถ์Œ์˜ ์ˆซ์ž ์นด๋“œ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•˜์ž. ๊ฐ ๋ฌถ์Œ์˜ ์นด๋“œ์˜ ์ˆ˜๋ฅผ A, B๋ผ ํ•˜๋ฉด ๋ณดํ†ต ๋‘ ๋ฌถ์Œ์„ ํ•ฉ์ณ์„œ ํ•˜๋‚˜๋กœ ๋งŒ๋“œ๋Š” ๋ฐ์—๋Š” A+B ๋ฒˆ์˜ ๋น„๊ต๋ฅผ ํ•ด์•ผ ํ•œ๋‹ค. ์ด๋ฅผํ…Œ๋ฉด, 20์žฅ์˜ ์ˆซ์ž ์นด๋“œ ๋ฌถ์Œ๊ณผ 30์žฅ

www.acmicpc.net



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

  • ์นด๋“œ ๋ฌถ์Œ๋“ค์„ ํ•ฉ์น ๋•Œ ์ตœ์†Œ ๋น„๊ต ํšŸ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

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

  • ์ž‘์€ ๋ฌถ์Œ๋ถ€ํ„ฐ ํ•ฉ์ณ์•ผ ์ตœ์†Œ๊ฐ’์ด ๋‚˜์˜ค๋Š”๊ฑธ ๋ฌธ์ œ์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ,
    ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ์ ‘๊ทผํ•ด ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ’€์ดํ•œ๋‹ค.
  • ๋‘ ์ตœ์†Œ๊ฐ’ ์›์†Œ๋ฅผ ๋ฝ‘์•„ ๊ทธ ํ•ฉ์„ ์ •๋‹ต์— ๋ˆ„์ ํ•˜๊ณ , ๋‹ค์‹œ ๊ทธ ํ•ฉ์„ ์šฐ์„ ์ˆœ์œ„ ํ์— ๋„ฃ๋Š”๋‹ค.
    • ์šฐ์„ ์ˆœ์œ„ ํ์˜ ์›์†Œ๊ฐ€ 1๊ฐœ๊ฐ€ ๋‚จ์„ ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.
    • ํ•ฉ์œผ๋กœ ๋งŒ๋“ค์–ด์ง„ ์ƒˆ ๋ฌถ์Œ์ด ๊ธฐ์กด ๋ฌถ์Œ๋ณด๋‹ค ํด ์ˆ˜ ์žˆ์Œ์— ์œ ์˜ํ•œ๋‹ค.

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

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

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());
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        for (int i = 0; i < N; i++) {
            pq.add(Integer.parseInt(br.readLine()));
        }

        int answer = 0;
        int n1, n2;

        while (pq.size() > 1) {
            n1 = pq.poll();
            n2 = pq.poll();
            answer += n1 + n2;
            pq.add(n1 + n2);
        }

        bw.write(Integer.toString(answer));
        bw.flush();
    }
}

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

  • N๊ฐœ์˜ ๋ฌถ์Œ์„ ์šฐ์„ ์ˆœ์œ„ ํ pq์— ์ €์žฅํ•œ๋‹ค.
  • pq์˜ ํฌ๊ธฐ๊ฐ€ 1์ด ๋  ๋•Œ๊นŒ์ง€, ์›์†Œ๋ฅผ 2๊ฐœ์”ฉ ๊บผ๋‚ด ๊ทธ ํ•ฉ์„ ๋ˆ„์ ํ•˜๊ณ , ๋‹ค์‹œ pq์— ๋„ฃ๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•œ๋‹ค.
  • ์ตœ์ข…์œผ๋กœ ๋ˆ„์ ๋œ answer์˜ ๊ฐ’์ด ์ •๋‹ต์ด๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ๊ทธ๋ฆฌ๋””์ ์œผ๋กœ ์ ‘๊ทผํ•ด์„œ ๋‹จ์ˆœํžˆ ์ตœ์†Œ๊ฐ’๋งŒ ๋ˆ„์ ํ•˜๋ฉด ๋˜๋Š” ์ค„ ์•Œ์•˜๋Š”๋ฐ, ์ƒˆ๋กœ ๋งŒ๋“ค์–ด์ง„ ๋ฌถ์Œ์˜ ํฌ๊ธฐ๊ฐ€ ๊ธฐ์กด ๊ฐ’๋ณด๋‹ค ๋” ํด ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์‹œ ์šฐ์„ ์ˆœ์œ„ ํ์— ๋„ฃ์–ด์ฃผ์–ด์•ผ ํ–ˆ๋‹ค.
    • ์ด ๋ถ€๋ถ„์„ ๊ตฌํ˜„ํ•˜์ง€ ์•Š์•„์„œ 1ํšŒ ํ‹€๋ ธ๋‹ค.

 

728x90

'CodingTest > Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ_11444 : ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜ 6  (0) 2024.02.12
BOJ_1744 : ์ˆ˜ ๋ฌถ๊ธฐ  (0) 2024.02.11
BOJ_1300 : K๋ฒˆ์งธ ์ˆ˜  (0) 2024.02.05
BOJ_2343 : ๊ธฐํƒ€ ๋ ˆ์Šจ  (0) 2024.02.05
BOJ_11404 : ํ”Œ๋กœ์ด๋“œ  (0) 2024.01.31