Post

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

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

문제 링크


1. 문제 풀이


주어진 아이들을 오름차순으로 정렬하기 위한 최소 횟수를 구하는 문제로 옮길 아이는 임의의 위치에 배치할 수 있다는 점에서 초기 아이들의 번호에 대한 LIS를 구한 후 LIS에 포함되지 않은 아이들을 적절한 위치에 배치하면 오름차순으로 정렬하면서 최소 횟수로 이동시킬 수 있다.


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
30
31
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));

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

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

        int[] dp = new int[n];
        Arrays.fill(dp, 1);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (arr[i] > arr[j]) dp[i] = Math.max(dp[i], dp[j] + 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
21
22
#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(n, 1);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (v[i] > v[j]) dp[i] = max(dp[i], dp[j] + 1);
        }
    }

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

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