Skip to content

Commit 9ed92ce

Browse files
committed
Longest increasing subsequence
1 parent 541a578 commit 9ed92ce

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

LIS.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
using namespace std;
4+
5+
void printLIS(vector<ll> &a, vector<ll> &prev, int pos) {
6+
if(pos<0)
7+
return;
8+
printLIS(a, prev, prev[pos]);
9+
cout<<a[pos]<<" ";
10+
}
11+
12+
void LIS(vector<ll> &a) {
13+
int i,j,maxim = 0,n = a.size();
14+
vector<ll> LIS(n,1);
15+
vector<ll> prev(n,-1);
16+
for(i=0; i<n; i++) {
17+
for(j=0; j<i; j++) {
18+
if(a[i] > a[j] && LIS[i] < LIS[j]+1) {
19+
LIS[i] = LIS[j] + 1;
20+
prev[i] = j;
21+
}
22+
}
23+
}
24+
int pos = 0;
25+
for(i=0; i<n; i++) {
26+
if(LIS[i] > maxim) {
27+
maxim = LIS[i];
28+
pos = i;
29+
}
30+
}
31+
cout<<"Length of LIS = "<<maxim<<endl;
32+
printLIS(a,prev,pos);
33+
cout<<endl;
34+
}
35+
36+
int main() {
37+
ll i,n;
38+
cin>>n;
39+
vector<ll> a(n);
40+
for(i=0; i<n; i++) {
41+
cin>>a[i];
42+
}
43+
LIS(a);
44+
return 0;
45+
}

0 commit comments

Comments
 (0)