Post

BOJ_14002_가장 긴 증가하는 부분 수열 4 (Java, C++)

BOJ_14002_가장 긴 증가하는 부분 수열 4 (Java, C++)

[Gold IV] 가장 긴 증가하는 부분 수열 4 - 14002

문제 링크

성능 요약

메모리: 2020 KB, 시간: 0 ms

분류

다이나믹 프로그래밍

제출 일자

2025년 1월 15일 23:07:25

문제 설명

수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오.

예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {10, 20, 10, 30, 20, 50} 이고, 길이는 4이다.

입력

첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000)이 주어진다.

둘째 줄에는 수열 A를 이루고 있는 Ai가 주어진다. (1 ≤ Ai ≤ 1,000)

출력

첫째 줄에 수열 A의 가장 긴 증가하는 부분 수열의 길이를 출력한다.

둘째 줄에는 가장 긴 증가하는 부분 수열을 출력한다. 그러한 수열이 여러가지인 경우 아무거나 출력한다.

문제 풀이

유명한 유형인 LIS 유형이다. 이제 역추적까지 곁들인 문제다. 역추적 부분은 dp 배열에서 최대 길이찾고 -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
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
/**
 * Author: nowalex322, Kim HyeonJae
 */
import java.io.*;
import java.util.*;

public class Main {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;
	static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws Exception {
		new Main().solution();
	}

	public void solution() throws Exception {
		br = new BufferedReader(new InputStreamReader(System.in));
//		br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int N = Integer.parseInt(br.readLine());
		int[] arr = new int[N+1];
		int[] dp = new int[N+1];
		Arrays.fill(dp, 1);
		
		st = new StringTokenizer(br.readLine());
        for(int i=1; i<=N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        
		List<Integer> res = new ArrayList<Integer>();
		int maxLen = 1;
		for(int i=1; i<=N; i++) {
			for(int j=1; j<i; j++) {
				if(arr[i] > arr[j]) dp[i] = Math.max(dp[i], dp[j]+1);
			}
			maxLen = Math.max(maxLen, dp[i]);
		}

		// 역추적
		int len = maxLen;
        for(int i=N; i>=1; i--) {
            if(dp[i] == len) {
                res.add(arr[i]);
                len--;
            }
        }
		sb.append(maxLen).append("\n");
		for(int i=res.size()-1; i>=0; i--) {
            sb.append(res.get(i) + " ");
        }
		bw.write(sb.toString());
		bw.flush();
		bw.close();
		br.close();
	}
}

C++ 코드

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
58
59
60
61
62
63
64
65
/**
 * Author: nowalex322, Kim HyeonJae
 */
#include <bits/stdc++.h>
using namespace std;

// #define int long long
#define MOD 1000000007
#define INF LLONG_MAX
#define ALL(v) v.begin(), v.end()

#ifdef LOCAL
#include "algo/debug.h"
#else
#define debug(...) 42
#endif

void solve() {
    int n;
    cin >> n;
    vector<int> arr(n + 1);
    vector<int> dp(n + 1, 1);

    for (int i = 1; i <= n; i++) {
        cin >> arr[i];
    }

    int maxLen = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j < i; j++) {
            if (arr[i] > arr[j]) {
                dp[i] = max(dp[i], dp[j] + 1);
            }
        }
        maxLen = max(maxLen, dp[i]);
    }

    // 역추적
    vector<int> result;
    int len = maxLen;
    for (int i = n; i >= 1; i--) {
        if (dp[i] == len) {
            result.push_back(arr[i]);
            len--;
        }
    }

    cout << maxLen << "\n";
    for (int i = result.size() - 1; i >= 0; i--) {
        cout << result[i] << " ";
    }
}

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

    int tt = 1;  // 기본적으로 1번의 테스트 케이스를 처리
    // cin >> tt;    // 테스트 케이스 수 입력 (필요 시)

    while (tt--) {
        solve();
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.