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