Skip to content

Commit f5037d2

Browse files
committed
Add code for longest bitonic subsequence
1 parent 24a1a30 commit f5037d2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

LongestBitonicSequence.cpp

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

0 commit comments

Comments
 (0)