Programming algorithms-Longest ascending subsequence problem code (C)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.