最长公共子序列(LCS)最长递增子序列(LIS)

#include<cstring>
#include<iostream>
#include<stack>
#include <algorithm>
using namespace std;

int dp[100][100];
char D[100][100];
stack<char> st;
string s1,s2;
int LCS(string s1,string s2)
{
for(int i=0;i<100;i++)
{
dp[i][0] = dp[0][i] = 0;
}
for(int i=0;i<s1.length();i++)
for(int j=0;j<s2.length();j++)
{
if(s1[i] == s2[j])
{
dp[i][j] = dp[i-1][j-1]+1;
D[i][j] = 'x';
}
else
{
dp[i][j] = dp[i-1][j] > dp[i][j-1]?dp[i-1][j] : dp[i][j-1];
if(dp[i-1][j] > dp[i][j-1])
{
dp[i][j] = dp[i-1][j];
D[i][j] = 's';
}
else
{
dp[i][j] = dp[i][j-1];
D[i][j] = 'z';
}
}
}
int p = s1.length()-1;
int q = s2.length()-1;
while(p>=0&&q>=0)
{

if(D[p][q] == 'z')
{
q--;
}
else if(D[p][q] == 's')
{
p--;
}
else if(D[p][q] == 'x')
{
st.push(s1[p]);//反向输出
p--;
q--;
}
}
while(!st.empty())
{
cout<<st.top();
st.pop();
}
cout<<endl;
return dp[s1.length()-1][s2.length()-1];
}
int main()
{
//LCS
//cin>>s1>>s2;
//cout<<LCS(s1,s2)<<endl;
//LIS
cin>>s1;
s2 = s1;
sort(s2.begin(),s2.end());
cout<<LCS(s1,s2)<<endl;
return 0;
}

posted @   mc宇少  阅读(141)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示