首页 技术 正文
技术 2022年11月6日
0 收藏 897 点赞 337 浏览 1352 个字

http://poj.org/problem?id=1458

一道容易的DP,求最长公共子序列的

dp[i][j],代表str1中的第i个字母和str2中的第j个字母的最多的公共字母数

 #include <stdio.h>
#include <iostream>
#include <string.h> using namespace std;
int dp[][]={}; int main()
{
char str1[],str2[];
while(~scanf("%s %s",str1,str2))
{
/* scanf("%s",str1)
scanf("%s",str2);*/
int len1=strlen(str1);
int len2=strlen(str2);
for(int i=;i<=len1;i++)
for(int j=;j<=len2;j++)
{
if(str1[i-]==str2[j-]) dp[i][j]=dp[i-][j-]+; //这个就是那个递推公式,但str1[i-1]和str2[j-1]想等于时dp[i][j]就会等于前一个加一,不等就是等于前面的最大的一个
else dp[i][j]=max(dp[i-][j],dp[i][j-]);
}
printf("%d\n",dp[len1][len2]);
}
return ;
}

http://poj.org/problem?id=1159

这个是POJ1159的题目,试求插入的最少的字符,使其变成回文字符串

这个最少的字符MIN=N-N和N的逆序数的最长公共子序列

所以这道题也就是和上面的那个题目一样,求最长的公共子序列,不过有一个地方比上面要特殊一点,就是数组只可以开滚动数组,不然POJ就爆内存

也只是在部分地方进行了改动即可

在这里也使用了一个我以前从未用过的函数,reverse ,这个函数在algorithm的头文件里

作用是把远数组变成逆序的,使用方法也就是reverse(begin(),end());

 #include <stdio.h>
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm> using namespace std; int dp[][];
string str1,str2; int main(){
int n;
while(scanf("%d",&n)!=EOF){
cin>>str1;
str2=str1;
memset(dp,,sizeof(dp));
reverse(str2.begin(),str2.end());
for(int i=;i<=n;i++)
for(int j=;j<=n;j++){
if(str1[i-]==str2[j-]){
int tem=dp[(i-)%][j-]+; //这个和上面的不同的原因在于这个是滚动数组,而滚动数组的话,原数组一般都是有值的,只不过是新的值在原数组上进行覆盖而已,求最大的公共子序列,就不能排除原来的数组的dp[i%2][j]会小于tmp;
dp[i%][j]=max(dp[i%][j],tem);
}
else dp[i%][j]=max(dp[(i-)%][j],dp[i%][j-]);
}
cout<<n-dp[n%][n]<<endl;
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901