0% found this document useful (0 votes)
23 views2 pages

Assignment2# REG - 2014086

The document discusses solving the Longest Increasing Subsequence problem using dynamic programming to find the length of the longest subsequence and also print out the actual subsequence. It includes C++ source code implementing dynamic programming to solve the problem in O(n^2) time by storing the longest subsequence lengths and pointers to predecessors in arrays to backtrack the final subsequence.

Uploaded by

Fida Hussain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

Assignment2# REG - 2014086

The document discusses solving the Longest Increasing Subsequence problem using dynamic programming to find the length of the longest subsequence and also print out the actual subsequence. It includes C++ source code implementing dynamic programming to solve the problem in O(n^2) time by storing the longest subsequence lengths and pointers to predecessors in arrays to backtrack the final subsequence.

Uploaded by

Fida Hussain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Assignment # 02

Question: 1
Solution: it’s a Longest Increasing Subsequence problem, we can solve this
using a straight-forward dynamic programming solution in O(n2) time (which is
quick enough to get AC) but we need to print the sequence.

Source Code:
#include <iostream>

#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
#include <set>
using namespace std;
int main(){
int T,N;
cin>>T;
getchar();
char ch [20]; gets (ch);
while(T--){
int a;
vector<int> Tab;
while (gets(ch) && strlen(ch)) {
Tab.push_back(atoi(ch));
}
int MaxLIS=1;
int DP[Tab.size()];
int Path[Tab.size()];
for(int i=0;i<Tab.size();i++){
Path[i]=i;}
memset(DP,0,Tab.size()*sizeof(int));
DP[0]=1;
for(int i=1;i<Tab.size();i++){
DP[i]=1;
for(int j=0;j<i;j++){
if (Tab[j]<Tab[i]){
if ((1+DP[j])>DP[i]){
DP[i]=1+DP[j];
Path[i]=j;}
}
}
}
int idx=distance(DP,max_element(DP,DP+Tab.size()));
cout<<"Max hits: "<<DP[idx]<<endl;
vector<int> Solution;
while(Path[idx]!=idx){
Solution.push_back(Tab[idx]);
idx=Path[idx];}
Solution.push_back(Tab[idx]);
for(int i=Solution.size()-1;i>=0;i--){
cout<<Solution[i]<<endl;}
if (T!=0) cout<<endl;
}
return 0;}

You might also like