【简单dp】poj 2127 Greatest Common Increasing Subsequence【最长公共上升子序列】【模板】
2024-10-19 14:29:44
Sample Input
5
1 4 2 5 -12
4
-12 1 2 4
Sample Output
2
1 4 题目:给你两个数字序列,求出这两个序列的最长公共上升子序列。
输出最长的长度,并打表输出。可能存在多种正确答案,故此题是special judge! 分析:dp[i][j] : A[1...i]和B[1...j]的公共上升子序列中以B[j]为结尾的最长的长度。
如果A[i] != B[j], 则dp[i][j]=d[i-1][j]; 也就是说当前这个A[i]是没效用的。
如果A[i] = B[j], 则dp[i][j]=max( dp[i][k]+1 ),其中 k<j 且 A[i]>B[k]
时间复杂度O(n^2) 注意:
n1 n2位两个序列的长度,
A[] B[]为两个序列数组,
ans 全局变量 最长公共子序列的长度值
lcis 最长公共上升子序列 打表存储 代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <iostream>
#include <string>
#include <algorithm> using namespace std; int n1, n2;
int A[510], B[510];
int dp[510][510];
int pre[510][510];
int lcis[510];
int ans; void get_LCIS()
{
memset(dp, 0, sizeof(dp));
memset(pre, 0, sizeof(pre));
int i, j;
for(i=1; i<=n1; i++){
int k=0;
for(j=1; j<=n2; j++){
if(A[i] != B[j]) dp[i][j]=dp[i-1][j];
if(A[i]>B[j] && dp[i][j]>dp[i][k]) k=j;
if(A[i]==B[j]){
dp[i][j]=dp[i][k]+1;
pre[i][j]=k;
}
}
}
ans=-1;
int x=n1, y=0;
for(i=1; i<=n2; i++){
if(dp[n1][i]>ans){
ans=dp[n1][i]; y=i;
}
}
int cnt=1;
while(dp[x][y]){
if(A[x] != B[y]) x--;
else{
lcis[ans-cnt]=B[y];
cnt++;
y=pre[x][y];
}
}
} int main()
{
scanf("%d", &n1);
for(int i=1; i<=n1; i++) scanf("%d", &A[i]);
scanf("%d", &n2);
for(int i=1; i<=n2; i++) scanf("%d", &B[i]); get_LCIS();
printf("%d\n", ans );
for(int i=0; i<ans; i++)
printf("%d%c", lcis[i], i==ans-1?'\n':' '); return 0;
}
最新文章
- java web后台开发SSM框架(Spring+SpringMVC+MyBaitis)搭建与优化
- java.util.NoSuchElementException: Timeout waiting for idle object
- Java api 入门教程 之 JAVA的SYSTEM类
- codeforces195c
- 深入剖析 redis 事件驱动
- kvm虚拟化管理平台WebVirtMgr部署-完整记录(安装Windows虚拟机)-(4)
- php dirname(__FILE__) 获取当前文件的绝对路径
- JDBC第一次学习
- ASP.NET MVC中防止跨站请求攻击(CSRF)
- Dialog式的Activity(AndroidActivity生命周期)
- 已经不再更新新浪、网易及CSDN博客了!
- JavaScript动态更改页面元素
- Ubuntu 配置FTP服务器
- Spring Cloud(十二):分布式链路跟踪 Sleuth 与 Zipkin【Finchley 版】
- objective-c数组的七种遍历方法总结
- 【转载】chown和chmod使用
- ES6新特性概述
- 一个ping大包不通问题的解决过程
- 解决Ubuntu无法进行SSH连接的问题(以及如何使用SSH)
- ssh stricthostkeychecking=0
热门文章
- iOS 集成阿里百川最新版(3.1.1.96) 实现淘宝授权登录以及调用淘宝客户端商品详情页
- [Python2.x] 利用commands模块执行Linux shell命令
- Yii 2 的安装 之 踩坑历程
- filter、map函数的区别
- 错误命令“if not exist ";\Dll"; mkdir ";\Dll"; xcopy ";\bin\Debug\*.*"; ";F:\647\VS项目\EtrolMes2014SY\Framework\Dll"; /e /i /y”已退出,代码为 9009
- 哈工大LTP
- svn 更新文件冲突,提示中文乱码解决
- 【BZOJ3277/3473】串/字符串 后缀数组+二分+RMQ+双指针
- 《挑战程序设计竞赛》2.1 广度优先搜索 AOJ0558 POJ3669 AOJ0121
- redis集群报错,(error) MOVED 15495 127.0.0.1:7003