Longest ascending sub-sequence problem code (C)
This address: Http://blog.csdn.net/caroline_wendy
Title: There is a series A that is long n. Request the length of the longest ascending subsequence in this sequence. The number of the longest ascending subsequence can be spaced.
That is, the longest ascending subsequence (LIS, longest increasing subsequence), such as: N=5, a={4,2,3,1,5}, Result=3 (2,3,5).
Use dynamic solver (DP).
Method 1: The longest ascending subsequence before each number is calculated sequentially, and the time Complexity O (n^2).
Method 2: Find the oldest sequence for the last element, update the array with a smaller element, apply a binary search lookup element, time complexity (NLOGN).
Code:
/* * main.cpp * * Created on:2014.7.20 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <stdio.h>/* * m Ain.cpp * * Created on:2014.7.20 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <stdio.h> #include < ;memory.h> #include <limits.h> #include <algorithm>using namespace Std;class program {static const int MAX _n = 100;const int INF = Int_max>>2;int N = 5;int A[max_n] = {4, 2, 3, 1, 5};int Dp[max_n];p ublic:void solve () {int res = 0;for (int i=0; i<n; ++i) {Dp[i] = 1;for (int j=0; j<i; ++j) {if (A[j]<a[i]) {Dp[i] = max (Dp[i], dp[j]+1);} }res = max (res, dp[i]);} printf ("result =%d\n", res);} void Solve2 () {Fill (DP, Dp+n, INF), for (int i=0; i<n; i++) {*lower_bound (DP, Dp+n, a[i]) = A[i];} printf ("result =%d\n", Lower_bound (DP, Dp+n, INF)-DP);}}; int main (void) {program ip;ip.solve2 (); return 0;}
Output:
result = 3
Programming algorithms-Longest ascending subsequence problem code (C)