[백준] 12738번 - 가장 긴 증가하는 부분 수열 3 [Java][C++]
[백준] 12738번 - 가장 긴 증가하는 부분 수열 3 [Java][C++]
1. 문제 풀이
수열 $A$ 에 대한 가장 긴 증가하는 부분 수열의 길이를 구하는 문제로 전형적인 LIS 알고리즘을 활용하는 문제다. 수열의 크기 $N$ 이 최대 $1,000,000$ 이어서 2중 반복문 대신 이분 탐색 LIS를 활용하면 간단하게 해결할 수 있다.
2. 코드
1. 이분 탐색 LIS [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
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());
}
List<Integer> dp = new ArrayList<>();
for (int n : arr) {
int idx = lowerBound(dp, n);
if (idx == dp.size()) {
dp.add(n);
} else {
dp.set(idx, n);
}
}
System.out.println(dp.size());
}
static int lowerBound(List<Integer> list, int key) {
int left = 0;
int right = list.size();
while (left < right) {
int mid = (left + right) / 2;
if (list.get(mid) < key) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
}
2. 이분 탐색 LIS [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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
vector<int> dp;
for (int x : v) {
auto it = lower_bound(dp.begin(), dp.end(), x);
if (it == dp.end()) {
dp.push_back(x);
} else {
*it = x;
}
}
cout << dp.size();
}
3. 풀이 정보
1. 이분 탐색 LIS [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 636 ms | 133300 KB | 1135 B |
2. 이분 탐색 LIS [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 172 ms | 12200 KB | 434 B |
This post is licensed under CC BY 4.0 by the author.