[BOJ] 2565번 전깃줄 - C++

"다이나믹 프로그래밍"

Posted by Yongmin on June 9, 2021

문제

전깃줄

풀이

LIS 문제 응용이라고 할 수 있다. 전깃줄이 교차하지 않으려면 전깃줄 번호의 오름차순으로 연결되어야 교차하지 않는다. 그러므로, 부분 수열 중 가장 긴 부분 수열의 수를 전체에서 빼주면 원하는 답이 나온다. 그전에 A 전깃줄이 순서대로 어떻게 연결되어 있는지 정렬을 하고 난 뒤(A전깃줄 번호를 index로 칭하여 그에 해당되는 arr값을 연결된 B전깃줄 번호라고 칭하였다. 그 사이사이에 있는 0을 제거하기 위해 다시 vector함수로 0이 아닌 수를 옮겨 담았다.) LIS를 구하였다.

소스 코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//8 2 9 1 4 6 7 10
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int desc(int a, int b){
    return a>b;
}

int main(){
    int N;
    scanf("%d", &N);
    
    int map[501] = {0};
    int index_max = 0;
    for(int i = 1; i<=N; i++){
        int index;
        scanf("%d", &index);
        
        if(index_max<index){
            index_max = index;
        }
        
        scanf("%d", &map[index]);
    }
    
    vector<int> arr;
    for(int i = 1; i<=index_max; i++){
        if(map[i] != 0){
            arr.push_back(map[i]);
        }
    }

    
    
    int dp[501] = {0};
    dp[0] = 1;
    
    for(int i = 1; i<arr.size(); i++){
        int result_max = 0;
        for(int j = 0; j<i; j++){
            if(arr[i] > arr[j]){
                result_max = max(result_max, dp[j]);
            }
        }
        dp[i] = result_max + 1;
    }
    int dp_max = 0;
    for(int i = 0; i<arr.size(); i++){
        if(dp_max < dp[i]) dp_max = dp[i];
    }
    printf("%d\n", N-dp_max);
    

    
}



# # #