티스토리 뷰

https://www.acmicpc.net/problem/11053

 

 

11053번: 가장 긴 증가하는 부분 수열

수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오. 예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {10, 20, 10, 30, 20, 50} 이고, 길이는 4이다.

www.acmicpc.net

흔히 LIS라고 불리는 문제이다. 

 

dp[i]= numbers[i]로 끝나는 부분 수열을 의미한다. 

dp[i]는 dp[j]+1이다. 단, numbers[j] < numbers[i] && dp[i] < dp[j] + 일 때만 적용된다. 이유는 numbers[i]보다 numbers[j]값이 작아야 할것이며 길이도 1적은것보다 작아야 하기 때문이다.

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
 
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int[] dp = new int[num + 1];
        int[] numbers = new int[num + 1];
        for (int i = 1; i < num + 1; i++) {
            numbers[i] = sc.nextInt();
        }
        dp[0= 0;
        dp[1= 1;
        
        for (int i = 1; i <= num; i++) {
            for (int j = 1; j < i; j++) {
                if (numbers[j] < numbers[i] && dp[i] < dp[j] + 1) {
                    dp[i] = dp[j] + 1;
                }
            }
        }
        Arrays.sort(dp);
 
        System.out.println(dp[num]);
 
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
댓글