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

用dp[i][j]表示处理到第1个字符的第i个,第二个字符的第j个时的最长LCS。

1、如果str[i] == sub[j],那么LCS长度就可以+1,是从dp[i - 1][j - 1] + 1,因为是同时捂住这两个相同的字符,看看前面的有多少匹配,+1后就是最大长度。

2、如果不同,那怎么办? 长度是肯定不能增加的了。

可以考虑下删除str[i] 就是dp[i - 1][j]是多少,因为可能i - 1匹配了第j个。也可能删除sub[j],就是dp[i][j - 1],因为可能str[i] == sub[j - 1]。同时考虑这两种情况的话,就是取max了。

因为只和上一维有关,所以可以用滚动数组来完成。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL; #include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string> const int maxn = 1e4 + ;
char str[maxn];
char sub[maxn];
int dp[][maxn];
void work() {
int now = ;
int lenstr = strlen(str + );
int lensub = strlen(sub + );
memset(dp, , sizeof dp);
for (int i = ; i <= lenstr; ++i) {
for (int j = ; j <= lensub; ++j) {
if (str[i] == sub[j]) {
dp[now][j] = dp[!now][j - ] + ;
} else {
dp[now][j] = max(dp[now][j - ], dp[!now][j]);
}
}
now = !now;
}
cout << dp[!now][lensub] << endl;
} int main() {
#ifdef local
freopen("data.txt","r",stdin);
#endif
IOS;
while (cin >> str + >> sub + ) work();
return ;
}

最新文章

  1. logstash服务启动脚本
  2. x01.TodoList:Asp.Net 5 初探
  3. WCF技术内幕 第二章 - 简单的Message
  4. iOS多播放器封装
  5. asp.net(C#)网站发布后 Global.asax 里 Application_Error 不执行的问题
  6. Texture tiling and swizzling
  7. 多级反向代理下,Java获取请求客户端的真实IP地址多中方法整合
  8. OProfile 性能分析工具
  9. Mysql-学习笔记(==》函数的建立与使用 十)
  10. net-snmp的安装
  11. html5 + css3 + zepto.js实现的微信广告宣传页
  12. vue 如何点击按钮返回上一页
  13. PHP冒泡排序算法
  14. nginx的ngx_http_realip_module模块和http头X-Forwarded-For、X-Real-IP
  15. 保存canvas
  16. Hadoop概念学习系列之搭建(windows)Eclipse/MyEclipse远程操作(Linux上)hadoop2.2.0/hadoop2.6.0 出错集(三十五)
  17. //{{AFX_MSG、//{{AFX_VIRTUAL、//{{AFX_MSG_MAP、//{{AFX_DATA_INIT
  18. JS post 数组道后台
  19. 如何在ASP.NET页面中使用异步任务(PageAsyncTask)
  20. hive sql split 分隔符

热门文章

  1. MSP430G2553需要注意的一些参数
  2. bzoj1556 (DP)
  3. Messes in Reading Source Coding of SSD
  4. Java 高阶 —— native 关键字与 JNI
  5. 使用cygwin注意事项二
  6. SQL Server 2008将数据导出为脚本 [SQL Server]
  7. HDU 1143 Tri Tiling 递归问题
  8. linux下printf函数为什么不加\n就不能输出相关的内容 ?
  9. Outlook 开发2
  10. mfc为对话框添加启动画面