【动态规划】最长上升子序列 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 <= 1000Output
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 8Sample 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》
发表评论
呵呵 代码啊 不懂哦
懂一门语言是很必要的。
又见天书,闪!
。。。不解释。