Post

[BaekJoon] 7570번 - 줄 세우기 [Java][C++]

[BaekJoon] 7570번 - 줄 세우기 [Java][C++]

문제 링크


1. 문제 풀이


BaekJoon 2631번 - 줄세우기 문제에서 이제 옮길 때 가장 앞이나 뒤로만 옮길 수 있는 문제로 이전처럼 단순한 LIS로는 해결할 수 없다. 중간에 배치하는 것이 불가능하므로 LIS를 구하되 번호가 1씩 증가하는 LIS를 구하면 해당 LIS에 포함되지 않은 아이들을 적절하게 맨 앞이나 맨 뒤로 이동시켜서 최소 횟수로 오름차순으로 배치할 수 있다.

번호가 1씩 증가하는 LIS는 dp 테이블에서 이전 인덱스의 값을 바로 참조하면 되므로 $O(N)$ 의 시간복잡도로 구할 수 있다.


2. 코드


1. 풀이 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.io.*;
import java.util.*;

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

        int n = Integer.parseInt(br.readLine());

        int[] arr = new int[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int[] dp = new int[1 + n];
        for (int x : arr) {
            dp[x] = dp[x - 1] + 1;
        }

        int max = 0;
        for (int x : dp) {
            max = Math.max(max, x);
        }

        System.out.println(n - max);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    vector<int> dp(1 + n);
    for (int x : v) {
        dp[x] = dp[x - 1] + 1;
    }

    cout << n - *max_element(dp.begin(), dp.end());
}

This post is licensed under CC BY 4.0 by the author.