Skip to content

Commit ad0ed1f

Browse files
authored
Create Longest palindromic subsequence - DP.cpp
1 parent 7457693 commit ad0ed1f

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// Dynamic programming solution
2+
#include <bits/stdc++.h>
3+
#include <ext/rope>
4+
using namespace std;
5+
using namespace __gnu_cxx;
6+
7+
using ld = long double;
8+
using llint = long long;
9+
using ullint = unsigned long long;
10+
using pii = pair <int,int>;
11+
using pcc = pair <char,char>;
12+
using pss = pair <string,string>;
13+
using vi = vector <int>;
14+
using vb = vector <bool>;
15+
using vii = vi::iterator;
16+
17+
#define INF (1<<30)
18+
#define MOD 1000000007
19+
#define mp make_pair
20+
#define mt make_tuple
21+
#define all(c) c.begin(), c.end()
22+
#define ms(name,val) memset(name, val, sizeof name)
23+
#define np nullptr
24+
25+
26+
int n;
27+
string s;
28+
vector <vi> DP;
29+
30+
void printLPS()
31+
{
32+
string seq;
33+
int i = 0, j = n-1;
34+
35+
while (i <= j)
36+
{
37+
if (s[i] == s[j])
38+
{
39+
seq += s[j];
40+
++i, --j;
41+
}
42+
else
43+
{
44+
if (DP[i][j-1] > DP[i+1][j])
45+
--j;
46+
else
47+
++i;
48+
}
49+
}
50+
51+
int m = seq.size();
52+
53+
if (DP[0][n-1] & 1)
54+
{
55+
if (m == 1)
56+
cout << seq << '\n';
57+
else
58+
{
59+
string add = string(1, seq[m-1]);
60+
seq.pop_back();
61+
string rseq = seq;
62+
reverse(all(rseq));
63+
cout << seq << add << rseq << '\n';
64+
}
65+
}
66+
else
67+
{
68+
string rseq = seq;
69+
reverse(all(rseq));
70+
cout << seq << rseq << '\n';
71+
}
72+
}
73+
74+
int findLPS()
75+
{
76+
n = s.size();
77+
DP.resize(n);
78+
79+
for (int t1 = 0; t1 < n; ++t1)
80+
{
81+
DP[t1].resize(n);
82+
DP[t1][t1] = 1;
83+
}
84+
85+
for (int topCol = 1; topCol < n; ++topCol)
86+
{
87+
for (int i = 0, j = topCol; j < n; ++i, ++j)
88+
{
89+
if (s[i] == s[j])
90+
{
91+
DP[i][j] = 2; // maximal if len of sequence is 2
92+
if (j > i+1) DP[i][j] += DP[i+1][j-1];
93+
}
94+
else DP[i][j] = max(DP[i][j-1], DP[i+1][j]);
95+
// maximum by:
96+
// 1) ignoring letter s[i]
97+
// 2) ignoring letter s[j]
98+
}
99+
}
100+
101+
return DP[0][n-1];
102+
}
103+
104+
int main()
105+
{
106+
ios_base::sync_with_stdio(0);
107+
//cin.tie(0);
108+
109+
cin >> s;
110+
cout << findLPS() << '\n';
111+
printLPS();
112+
113+
114+
115+
return 0;
116+
}

0 commit comments

Comments
 (0)