Skip to content

Instantly share code, notes, and snippets.

@KoStard
Created August 18, 2017 13:21
Show Gist options
  • Save KoStard/11f70cccda70bed351125f73fb7d90b4 to your computer and use it in GitHub Desktop.
Save KoStard/11f70cccda70bed351125f73fb7d90b4 to your computer and use it in GitHub Desktop.
Dynamic programming
#include <iostream>
#include <vector>
using namespace std;
int calc(int temp, vector<int> &input, vector<int> &L, vector<vector<int>> &mem){
if(L.size()==0){
L.push_back(1);
mem.push_back(*new vector<int>(1,0));
return 1;
}
int max = -1, max_index = 0;
for(int i=0;i<L.size();i++){
if(input[i]<*(input.end()-1)){
if(max==-1) {
max = L[i];
max_index=i;
}
else{
if(L[i]>max) {
max=L[i];
max_index = i;
}
}
}
}
vector<int> t = mem[max_index];
t.push_back(input.size()-1);
mem.push_back(t);
L.push_back(max+1);
return max+1;
}
int main(){
int q;
cout << "Type the queries number: ";
cin >> q;
while(q--){
vector<int> input;
vector<int> L;
vector<vector<int>> mem;
int n;
cout << "Enter the size of vector: ";
cin >> n;
int max = -1;
for(int i=0;i<n;i++){
int temp;
cin >> temp;
input.push_back(temp);
int c = calc(temp, input, L, mem);
if(max==-1) max=c;
else if(c>max)max=c;
}
cout << "Done! Maximum length of increasing subsequence is: "<< max << endl;
for(int i=0;i<mem.size();i++)
if(mem[i].size()==max){
for(int j=0;j<mem[i].size();j++){
cout << input[mem[i][j]] << " ";
}
cout << endl;
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment