【动态规划】最长上升子序列 POJ2533

时间:2010年10月18日作者:坏男孩查看次数:1,277 views评论次数:4

最经典也是最简单的动态规划题目 

Description

A numeric sequence of ai is ordered if a1 < a2 < … < aN. Let the subsequence of the given numeric sequence (a1, a2, …, aN) be any sequence (ai1, ai2, …, aiK), where 1 <= i1 < i2 < … < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8).

Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.

Input

The first line of input file contains the length of sequence N. The second line contains the elements of sequence – N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000

Output

Output file must contain a single integer – the length of the longest ordered subsequence of the given sequence.

Sample Input

7
1 7 3 5 9 4 8

Sample Output

4

动态转移方程如下(这是O(n^2)级别的):b[i] = Max{b[j] + 1} (1 <= j < i 且 a[j] < a[i])

程序代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;
int a[5001], b[5001];
int main() {
    int i,j,n,summ=-1;
    cin>>n;
    for (i=1;i<=n;i++) {
        cin>>a[i];b[i]=1;
    }
    for (i=1; i <= n; i++) {
        for (j=1;j<i;j++)
            if (a[j]<a[i]&&b[j]+1>b[i]) {
                b[i]=b[j]+1; //方程:b[i] = Max{b[j] + 1} (1 <= j < i 且 a[j] < a[i])
            }
        summ=max(b[i],summ); //求最大的b[i] 
    }
    cout<<summ<<endl;
    //while (1);
    return 0;
}

声明: 本文采用 BY-NC-SA 协议进行授权 | 坏男孩的博客
转载请注明转自《【动态规划】最长上升子序列 POJ2533

标签:分类:C语言
4条评论
  1. su留言于:2010年10月19日12:56 回复

    呵呵 代码啊 不懂哦

    • 坏男孩留言于:2010年10月19日21:49 回复

      懂一门语言是很必要的。

  2. 黄伟涛留言于:2010年10月19日00:45 回复

    又见天书,闪!

发表评论

*

*

d9 d8 d7 d6 d56 d55 d54 d53 d52 d51 d50 d5 d49 d48 d47 d46 d45 d44 d43 d42 d41 d40 d4 d39 d38 d37 d36 d35 d34 d33 d32 d31 d30 d3 d29 d28 d27 d26 d25 d24 d23 d22 d21 d20 d2 d19 d18 d17 d16 d15 d14 d13 d12 d11 d10 d1