Output longest ascending subsequence model (DP)

Source: Internet
Author: User

To output the longest ascending subsequence, you only need to add a pre array to record the first of the newly added sequence. You can traverse the array once.

The Code is as follows:

# Include <iostream>
# Include <cstdio>
# Include <cstring>

Using namespace STD;

Const int n= 1000;

Int num [N];
Int pre [N];
Int DP [N];
Int f [N];


Int main ()
{
Freopen ("data. In", "r", stdin );
Int N, I, j, ANS, flag;
While (~ Scanf ("% d", & n ))
{
For (I = 1; I <= N; I ++)
Scanf ("% d", & num [I]);

Memset (DP, 0, sizeof (DP ));
Memset (PRE, 0, sizeof (pre ));
Memset (F, 0, sizeof (f ));
DP [1] = 1;
For (I = 2; I <= N; I ++)
{
Ans = DP [I];
For (j = 1; j <I; j ++)
{
If (Num [I]> num [J] & Ans <DP [J])
{
Ans = DP [J];
If (! Pre [num [I] &! F [J])
{
Pre [num [I] = num [J]; // record
F [J] = 1;
Flag = num [I];
}
}
}
DP [I] = ans + 1;
}
Ans = 0;
I = flag;
While (I)
{
Printf ("% d", I );
I = pre [I];
}
For (I = 1; I <= N; I ++)
If (DP [I]> ans)
Ans = DP [I];
Printf ("\ n % d \ n", ANS );
}
Return 0;
}

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.