๊ธฐ๋ก๋ฐฉ

BOJ_24060 : ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๋ณ‘ํ•ฉ ์ •๋ ฌ 1 ๋ณธ๋ฌธ

CodingTest/Java

BOJ_24060 : ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๋ณ‘ํ•ฉ ์ •๋ ฌ 1

Soom_1n 2023. 1. 23. 01:12

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

 

24060๋ฒˆ: ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๋ณ‘ํ•ฉ ์ •๋ ฌ 1

์ฒซ์งธ ์ค„์— ๋ฐฐ์—ด A์˜ ํฌ๊ธฐ N(5 ≤ N ≤ 500,000), ์ €์žฅ ํšŸ์ˆ˜ K(1 ≤ K ≤ 108)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ ์ค„์— ์„œ๋กœ ๋‹ค๋ฅธ ๋ฐฐ์—ด A์˜ ์›์†Œ A1, A2, ..., AN์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ Ai ≤ 109)

www.acmicpc.net



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

  • ์ฃผ์–ด์ง„ ์˜์‚ฌ ์ฝ”๋“œ๋กœ ๋ณ‘ํ•ฉ ์ •๋ ฌ์„ ๊ตฌํ˜„ํ•œ๋‹ค.

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

import java.util.Scanner;

public class Main {
    static int count, num;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        num = k;
        int[] a = new int[n];
        int[] tmp = new int[n+1];

        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        merge_sort(a, 0, n - 1, tmp);

        if (count < k) {
            System.out.println(-1);
        } else {
            System.out.println(num);
        }
    }

    private static void merge_sort(int[] a, int p, int r, int[] tmp) {
        if (p < r) {
            int q = (p + r) / 2;
            merge_sort(a, p, q, tmp);
            merge_sort(a, q + 1, r, tmp);
            merge(a, p, q, r, tmp);
        }
    }

    private static void merge(int[] a, int p, int q, int r, int[] tmp) {
        int i = p, j = q + 1, t = 1;

        while (i <= q && j <= r) {
            if (a[i] <= a[j]) {
                tmp[t++] = a[i++];
            } else {
                tmp[t++] = a[j++];
            }
        }
        while (i <= q) {
            tmp[t++] = a[i++];
        }
        while (j <= r) {
            tmp[t++] = a[j++];
        }
        i = p;
        t = 1;
        while (i <= r) {
            a[i++] = tmp[t++];
            if (++count == num) {
                num = tmp[t - 1];
            }
        }
    }
}

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

  • main ๋ฉ”์„œ๋“œ๋Š” ์ž…๋ ฅ ๊ฐ’ ์ €์žฅ๊ณผ ์˜์‚ฌ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•œ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
  • merge_sort ๋ฉ”์„œ๋“œ์—์„œ ์‹œ์ž‘ ์ธ๋ฑ์Šค p, ๋ ์ธ๋ฑ์Šค r์˜ ์ค‘๊ฐ„ ๊ฐ’์œผ๋กœ q๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
  • ๋‹ค์‹œ p~q, q+1~r ๊ฐ๊ฐ merge_sort๋ฅผ ๋‹ค์‹œ ๋Œ๋ฆฐ๋‹ค.(์žฌ๊ท€)
    • p๊ฐ€ r์ด์ƒ์ด ๋˜๋ฉด ์žฌ๊ท€๋ฅผ ์ข…๋ฃŒํ•œ๋‹ค.
    • merge_sort 2๋ฒˆ ํ›„ merge๋ฉ”์„œ๋“œ์—์„œ ๋ณ‘ํ•ฉ์„ ์‹คํ–‰ํ•œ๋‹ค.
      • ๋‘ ๋ฒ”์œ„๋ฅผ arr์— ํ•ฉ์ณ ๋„ฃ์œผ๋ฉด์„œ, ์ž‘์€๊ฑธ ๋จผ์ € ๋„ฃ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ •๋ ฌ์ด ์ด๋ฃจ์–ด ์ง„๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์˜์‚ฌ ์ฝ”๋“œ์— tmp ์„ ์–ธ์ด ๋น ์ ธ์žˆ์–ด์„œ ๋ณ‘ํ•ฉ ์ •๋ ฌ์˜ ๊ฐœ๋…์„ ๋‹ค์‹œ ์ฐพ์•„๋ณด์•˜๋‹ค. (ํฌ์ŠคํŒ…)

728x90

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

BOJ_11724 : ์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜  (0) 2023.01.23
BOJ_18870 : ์ขŒํ‘œ ์••์ถ•  (0) 2023.01.23
BOJ_25501 : ์žฌ๊ท€์˜ ๊ท€์žฌ  (0) 2023.01.20
BOJ_2566 : ์ตœ๋Œ“๊ฐ’  (0) 2023.01.19
BOJ_25305 : ์ปคํŠธ๋ผ์ธ  (0) 2023.01.18