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;
}
												

最新文章

  1. java web后台开发SSM框架(Spring+SpringMVC+MyBaitis)搭建与优化
  2. java.util.NoSuchElementException: Timeout waiting for idle object
  3. Java api 入门教程 之 JAVA的SYSTEM类
  4. codeforces195c
  5. 深入剖析 redis 事件驱动
  6. kvm虚拟化管理平台WebVirtMgr部署-完整记录(安装Windows虚拟机)-(4)
  7. php dirname(__FILE__) 获取当前文件的绝对路径
  8. JDBC第一次学习
  9. ASP.NET MVC中防止跨站请求攻击(CSRF)
  10. Dialog式的Activity(AndroidActivity生命周期)
  11. 已经不再更新新浪、网易及CSDN博客了!
  12. JavaScript动态更改页面元素
  13. Ubuntu 配置FTP服务器
  14. Spring Cloud(十二):分布式链路跟踪 Sleuth 与 Zipkin【Finchley 版】
  15. objective-c数组的七种遍历方法总结
  16. 【转载】chown和chmod使用
  17. ES6新特性概述
  18. 一个ping大包不通问题的解决过程
  19. 解决Ubuntu无法进行SSH连接的问题(以及如何使用SSH)
  20. ssh stricthostkeychecking=0

热门文章

  1. iOS 集成阿里百川最新版(3.1.1.96) 实现淘宝授权登录以及调用淘宝客户端商品详情页
  2. [Python2.x] 利用commands模块执行Linux shell命令
  3. Yii 2 的安装 之 踩坑历程
  4. filter、map函数的区别
  5. 错误命令“if not exist &quot;\Dll&quot; mkdir &quot;\Dll&quot; xcopy &quot;\bin\Debug\*.*&quot; &quot;F:\647\VS项目\EtrolMes2014SY\Framework\Dll&quot; /e /i /y”已退出,代码为 9009
  6. 哈工大LTP
  7. svn 更新文件冲突,提示中文乱码解决
  8. 【BZOJ3277/3473】串/字符串 后缀数组+二分+RMQ+双指针
  9. 《挑战程序设计竞赛》2.1 广度优先搜索 AOJ0558 POJ3669 AOJ0121
  10. redis集群报错,(error) MOVED 15495 127.0.0.1:7003