最長上升子序列(LIS)

LIS定義:

        最長上升子序列(Longest Increasing Subsequence,LIS),在計算機科學上是指一個序列中最長的單調遞增的子序列。

問題描述:

        這類問題一般表述爲:給一個數列,長度爲n,求LIS長度。

樣例輸入:

        循環每兩行輸入測試樣例,第一行輸入n,第二行輸入n個數字

9
5 1 3 6 8 2 9 0 10
5
1 2 4 0 2
9
2 7 1 5 6 4 3 8 9

樣例輸出:

        每個測試樣例,輸出一行LIS長度

6
3
5

 O(n^2)方法:

#include <cstdio>
#include <algorithm>
using namespace std;

const int N = int(2e5 + 5);

// 求LIS的長度O(n^2)
int g_d[N];
int LIS(const int arr[], const int &len)
{
    int i, j, ans = 0;
    for (i = 0; i < len; i++)
    {
        g_d[i] = 1;
        for (j = 0; j < i; j++)
        {
            if (arr[j] < arr[i]) g_d[i] = max(g_d[i], g_d[j] + 1);
        }
        ans = max(ans, g_d[i]);
    }
    return ans;
}

int main()
{
    int n, i;
    int a[N];
    while (scanf("%d", &n) != EOF)
    {
        for (i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        printf("%d\n", LIS(a, n));
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章