olrlobt

[์ž๋ฐ”/๋ฐฑ์ค€ ๊ณจ๋“œ5] #13164 ํ–‰๋ณต ์œ ์น˜์› ๋ณธ๋ฌธ

Algorithm/๋ฐฑ์ค€

[์ž๋ฐ”/๋ฐฑ์ค€ ๊ณจ๋“œ5] #13164 ํ–‰๋ณต ์œ ์น˜์›

olrlobt 2023. 1. 1. 19:37

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

 

๐Ÿ”’ ๊ณจ๋“œ5 - #13164 ํ–‰๋ณต ์œ ์น˜์› 

 

๐Ÿ“Œ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค ์ถ”๊ฐ€ ํžŒํŠธ

4 2
1 4 5 6

= 2

 

โœ๏ธ ํ’€์ด๋ฒ•

 

ํ•œ ์กฐ์—์„œ, ๊ฐ€์žฅ ํฐ ์‚ฌ๋žŒ๊ณผ ๊ฐ€์žฅ ์ž‘์€ ์‚ฌ๋žŒ์˜ ์ฐจ์ด๋Š” ๊ฐ ์กฐ์›์˜ ํ‚ค์˜ ์ฐจ์ด์˜ ํ•ฉ๊ณผ ๊ฐ™๋‹ค.

 

์˜ˆ๋กœ, ์œ„์˜ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด ์กฐ๋Š” 1 / 4, 5, 6 ๋‘ ๊ฐœ๋กœ ๋‚˜๋ˆ„์–ด์ง€๊ณ 

๋‘๋ฒˆ์งธ ์กฐ์—์„œ ๋น„์šฉ์€ (4์™€ 5์˜ ์ฐจ์ด) + (5์™€ 6์˜ ์ฐจ์ด) ์™€ ๊ฐ™๋‹ค.

 

๋”ฐ๋ผ์„œ ์กฐ๋ฅผ ๋‚˜๋ˆŒ๋•Œ๋Š”, ํ‚ค ์ฐจ์ด๊ฐ€ ๊ฐ€์žฅ ํฐ ์ˆœ์œผ๋กœ ์กฐ๋ฅผ ๋‚˜๋ˆ„์–ด์•ผ ํ•œ๋‹ค.

 

์œ„ ์˜ˆ์‹œ์—์„œ๋Š” ์กฐ๋ฅผ 2๊ฐœ๋กœ ๋‚˜๋ˆ„์—ˆ์œผ๋ฏ€๋กœ, 

์กฐ์› ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ํ•œ ๊ฐœ๋งŒํผ (= K-1) ์ง€์šด๋‹ค. 

 

 

 

 

 

ํ’€์ด๋ฐฉ๋ฒ•:

    1. ๋‹ค์Œ ์‚ฌ๋žŒ๊ณผ์˜ ํ‚ค ์ฐจ์ด๋ฅผ ๊ตฌํ•œ๋‹ค.

    2. ํ‚ค ์ฐจ์ด์—์„œ ํฐ ๊ฐ’๋ถ€ํ„ฐ K-1 ๋ฒˆ์งธ๊นŒ์ง€๋ฅผ ๋ชจ๋‘ ์ œ์™ธํ•˜๊ณ  ๋ชจ๋‘ ๋”ํ•œ๋‹ค.

 

 

๐Ÿ—๏ธ ํ’€์ด

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class baekjoon13164 {

    static List<Integer> height = new ArrayList<>();
    static List<Integer> heightGap = new ArrayList<>();
    static int K;

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

        int N = sc.nextInt();
        K = sc.nextInt();

        for (int testCase = 0; testCase < N; testCase++) {
            height.add(sc.nextInt());
        }

        solve();
    }

    public static void solve() {

        calHeightGap();
        calCost();
    }

    private static void calCost() {
        int sum = 0;

        for (int j = 0; j < heightGap.size() - K + 1; j++) {
            sum += heightGap.get(j);
        }

        System.out.println(sum);
    }

    private static void calHeightGap() {

        for (int i = 0; i < height.size() - 1; i++) {
            heightGap.add(height.get(i+1) - height.get(i));
        }
        Collections.sort(heightGap);
    }
}
Comments