티스토리 뷰
14002번: 가장 긴 증가하는 부분 수열 4
수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오. 예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {10, 20, 10, 30, 20, 50} 이
www.acmicpc.net
1. 문제
수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하고, 그 수열을 출력하는 문제.
2. 풀이
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] A = new int[N+1];
int[] D = new int[N+1];
int[] V = new int[N+1];
for (int i = 1; i <= N; i++) {
A[i] = sc.nextInt();
}
for (int i = 1; i <= N; i++) {
D[i] = 1;
int temp = 1;
int idx = 0;
for (int j = 1; j < i; j++) {
// 값이 작으면
if (A[i] > A[j]) {
if (D[i] + D[j] > temp) {
temp = D[i] + D[j];
idx = j;
}
}
}
D[i] = temp;
V[i] = idx;
}
int result = 0;
int resultIdx = 0;
for (int i = 1; i <= N; i++) {
if (result < D[i]) {
result = D[i];
resultIdx = i;
}
}
int[] resultArr = new int[result];
for (int i = resultArr.length-1; i >= 0; i--) {
resultArr[i] = A[resultIdx];
resultIdx = V[resultIdx];
}
System.out.println(result);
for (int i = 0; i < resultArr.length; i++) {
System.out.print(resultArr[i] + " ");
}
}
}
앞 문제와는 달리 길이와 그 수열까지 출력해줘야 함.
V라는 index값을 저장하는 배열을 하나 더 선언해서 해당 배열을 역추적해서 수열을 출력해줌.
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- non-blocking
- 비동기
- Asynchronous
- 인터셉터
- Handler Interceptor
- 논블로킹
- 필터
- 프로그래머스 Level 1
- 프로그래머스 Level 2
- a
- 프로그래머스 Level 3
- blocking
- 해시
- 프로그래머스
- Filter
- 코딩테스트 고득점 Kit
- Synchronous
- 핸들러 인터셉터
- 블로킹
- http://www.nextree.co.kr/p6960/
- 동기
- 스택/큐
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함