본문 바로가기
C#/백준 알고리즘

2022.02.08 [백준] C# 가장 긴 바이토닉 부분 수열

by ian's coding 2022. 2. 8.
728x90
반응형

 

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

 

11054번: 가장 긴 바이토닉 부분 수열

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

www.acmicpc.net

 


풀이

이 문제는 1~n까지의 LIS를 구해서 upper배열에 저장하고 반대로 n~1까지 LIS를 구해서 lower배열에 저장했다.

num의 배열에 순서대로 하면 최장 증가수열이고, 반대로 하면 최장 감소 수열이기 때문이다.

그리고 upper[i] + lower[i] -1 (-1을 해주는 이유는 i가 겹치기 때문)을 해주어 답을 구했다.

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
using System;
using System.Text;
using System.IO;
 
class Program
{
    static int[] num;
    static int[] upper;
    static int[] lower;
 
    static void Cal(int n)
    {
        for(int i = 2; i <= n; i++)
        {
            for(int j = 1; j < i; j++)
            {
                if (num[i] > num[j])
                {
                    upper[i] = Math.Max(upper[i], upper[j]+1);
                }
            }
            
        }
        for(int i = n-1; i > 0; i--)
        {
            for(int j = n; j > i; j--)
            {
                if (num[i] > num[j])
                {
                    lower[i] = Math.Max(lower[i], lower[j]+1);
                }
            }
            
        }
        
    }
 
    static void Main()
    {
        StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
        StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
        StringBuilder sb = new StringBuilder();
        int n = int.Parse(sr.ReadLine());
        num = new int[n + 1];
        upper = new int[n + 1];
        lower = new int[n + 1];
        string[] s = sr.ReadLine().Split();
        for(int i = 1; i <= n; i++)
        {
            num[i] = int.Parse(s[i - 1]);
            upper[i] = 1;
            lower[i] = 1;
        }
        Cal(n);
        int max = 0;
        for(int i = 1; i <= n; i++)
        {
            max = Math.Max(max, upper[i] + lower[i]);
        }
        sw.WriteLine(max - 1);
        sr.Close();
        sw.Close();
    }
}
cs

 

 

 

 

728x90
반응형

댓글