1 minute read

๐Ÿ“Œ ๋‚œ์ด๋„

๐Ÿฅ‡ Gold 4


๐Ÿ“Œ ๋ฌธ์ œ

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


image


๐Ÿ“Œ ํ’€์ด

์ด ๋ฌธ์ œ๋ฅผ ๋ณด์ž๋งˆ์ž๋“  ์ƒ๊ฐ์€ ๋ฐ”๋กœ DP๋ฅผ ์‘์šฉํ•˜์—ฌ ํ’€์–ด์•ผ๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด์˜€๋‹ค.
์ผ๋ฐ˜์ ์œผ๋กœ ์˜ค๋ฅธ์ชฝ์—์„œ ์™ผ์ชฝ๋กœ ๊ฐ€๋ฉด์„œ ์ด์ „์— ๊ฐ€์žฅ ํฐ๊ฐ’์ด ์žˆ๋Š”์ง€ ๋น„๊ต๋ฅผ ํ•˜๋ ค๋ฉด o(n^2/2)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ๋ฐœ์ƒํ•˜๋ฏ€๋กœ, ๋„ˆ๋ฌด๋‚˜๋„ ๊ธด ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๊ฒŒ ๋œ๋‹ค.
ํ•˜์ง€๋งŒ ๊ทธ๋ ‡๋‹ค๊ณ  ์ด์ „์— ๊ฐ€์žฅ ํฐ ๊ฐ’์ด ์–ด๋–ค๊ฑด์ง€๋งŒ ์ €์žฅ์„ ํ•ด๋†“์œผ๋ฉด, ์ตœ์ ํ•ด๊ฐ€ ๋‚˜์˜ค์ง€๋ฅผ ์•Š๋Š”๋‹ค.

์ด๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ์ฃผ์†Œ๊ฐ’์„ ์ €์žฅํ•˜๋Š” dp ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์„œ, ๊ทธ ์•ˆ์—๋Š” ๊ทธ๊ฒƒ๋ณด๋‹ค ํฐ ์˜ค๋ฅธ์ชฝ์— ์žˆ๋Š” ์ˆซ์ž์˜ ์ฃผ์†Œ๊ฐ’์ด ๋“ค์–ด๊ฐ€๊ฒŒ ํ•˜์˜€๋‹ค.

image


๐Ÿ“Œ Code

package BOJ.DS;

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

public class N17298 {
    static int[] nums;
    static int[] dp;

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

        int N = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());

        nums = new int[N];
        dp = new int[N];
        for (int i = 0; i < N; i++) {
            nums[i] = Integer.parseInt(st.nextToken());
        }

        FindNGE(N);
        ShowAll(N);
    }

    static void FindNGE(int N) {
        dp[N - 1] = -1;
        for (int i = N - 2; i >= 0; i--) {
            // ์ฃผ์†Œ๊ฐ’
            dp[i] = i + 1;
            // ์ฃผ์†Œ๊ฐ’์ด -1์ด ์•„๋‹ˆ๊ณ , ๋” ํฌ๋ฉด
            while (nums[i] >= nums[dp[i]]) {
                if (dp[dp[i]] != -1) {
                    dp[i] = dp[dp[i]];
                } else{
                    dp[i] = -1;
                    break;
                }
            }
        }
    }

    static void ShowAll(int N) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < N; i++) {
            if (dp[i] != -1) {
                sb.append(nums[dp[i]] + " ");
            } else {
                sb.append(-1 +" ");
            }
        }
        System.out.println(sb);
    }
}

package (์ด๋ฆ„); ๋ฅผ ๋•Œ๊ณ , class ์ด๋ฆ„์„ Main์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ๋œ๋‹ค.



๊ฐœ์ธ ๊ณต๋ถ€ ๊ธฐ๋ก์šฉ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹ค.
ํ‹€๋ฆฌ๊ฑฐ๋‚˜ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ์ œ๋ณดํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.๐Ÿ˜