Given a string S="abcdpcba".
The longest palindrome subsequences would be "abcdcba".
Program:-
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
string st;
cin>>st;
int arr[st.size()][st.size()]={0};
for(int i=0;i<st.size();i++)
arr[i][i]=1;
int len=2;
while(len<=st.size()){
for(int i=0;i<st.size()-len+1;i++)
{
int j=i+len-1;
if(st[i]==st[j])
arr[i][j]=arr[i+1][j-1]+2;
else arr[i][j]=max(arr[i][j-1],arr[i+1][j]);
}
len++;
}
cout<<arr[0][st.size()-1]<<endl;
vector< vector<string> >res;
res.resize( st.size() , vector<string>( st.size()) );
for(int i=0;i<st.size();i++)
res[i][i]=st[i];
len=2;
while(len<=st.size()){
for(int i=0;i<st.size()-len+1;i++)
{
int j=i+len-1;
if(st[i]==st[j] && len==2)
{ string temp;temp+=st[i];
temp+=st[j];
res[i][j]=temp;}
else if(st[i]==st[j])
res[i][j]=st[i]+res[i+1][j-1]+st[j];
else {
if(res[i][j-1].size() >res[i+1][j].size())
res[i][j]=res[i][j-1];
else res[i][j]=res[i+1][j];
}
}
len++;
}
cout<<res[0][st.size()-1]<<"\n";
return 0;
}
The longest palindrome subsequences would be "abcdcba".
Program:-
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
string st;
cin>>st;
int arr[st.size()][st.size()]={0};
for(int i=0;i<st.size();i++)
arr[i][i]=1;
int len=2;
while(len<=st.size()){
for(int i=0;i<st.size()-len+1;i++)
{
int j=i+len-1;
if(st[i]==st[j])
arr[i][j]=arr[i+1][j-1]+2;
else arr[i][j]=max(arr[i][j-1],arr[i+1][j]);
}
len++;
}
cout<<arr[0][st.size()-1]<<endl;
vector< vector<string> >res;
res.resize( st.size() , vector<string>( st.size()) );
for(int i=0;i<st.size();i++)
res[i][i]=st[i];
len=2;
while(len<=st.size()){
for(int i=0;i<st.size()-len+1;i++)
{
int j=i+len-1;
if(st[i]==st[j] && len==2)
{ string temp;temp+=st[i];
temp+=st[j];
res[i][j]=temp;}
else if(st[i]==st[j])
res[i][j]=st[i]+res[i+1][j-1]+st[j];
else {
if(res[i][j-1].size() >res[i+1][j].size())
res[i][j]=res[i][j-1];
else res[i][j]=res[i+1][j];
}
}
len++;
}
cout<<res[0][st.size()-1]<<"\n";
return 0;
}
No comments:
Post a Comment