首页 技术 正文
技术 2022年11月8日
0 收藏 351 点赞 2,099 浏览 1289 个字

Greatest Common Increasing Subsequence

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1432

题目大意:给出两串数字,求他们的最长公共上升子序列(LCIS),并且打印出来。

Sample Input

1

5
1 4 2 5 -12
4
-12 1 2 4

Sample Output

2
1 4

分析:神奇就神奇在是LIS与LCS的组合

令dp[i][j]表示A串的前i个,与B串的前j个,并以B[j]为结尾的LCIS 的长度.

状态转移方程:

  f(A[i]==B[j])   dp[i][j]=max(dp[i-1][k])+1;  ( 1 <= k < j )

  else   dp[i][j]=dp[i-1][j];

然后选择循环顺序,就可以将算法的复杂度降为n*n.

代码如下:

 /*这个代码结果虽然对,跟样例的输出都不一样,而且两个输出数据之间有空行都没有实现,却能AC,有点匪夷所思*/
# include<stdio.h>
# include<string.h>
#define MAX 550 struct node{
int x,y;
}path[MAX][MAX]; int dp[MAX][MAX];
int s[MAX],t[MAX]; int main(){
int T,i,j;
scanf("%d",&T);
while(T--)
{
memset(path,,sizeof(path));
int n,m;
scanf("%d",&n);
for(i=; i<=n; i++)
scanf("%d",&s[i]);
scanf("%d",&m);
for(i=; i<=m; i++)
scanf("%d",&t[i]);
memset(dp,,sizeof(dp));
int max = ;
for(i=; i<=n; i++)
{
max = ;
int tx = ,ty = ;
for(j=; j<=m; j++)
{
dp[i][j] = dp[i-][j];
path[i][j].x = i-;
path[i][j].y = j;
if( s[i] > t[j] && max < dp[i-][j])
{
max = dp[i-][j];
tx = i-;
ty = j;
}
if( s[i] == t[j] )
{
dp[i][j] = max+;
path[i][j].x = tx;
path[i][j].y = ty;
}
}
}
max = -;
int id;
for(i=; i<=m; i++)
if(dp[n][i]>max)
{
max = dp[n][i];
id = i;
}
int save[MAX];
int cnt=;
int tx,ty;
tx=n; ty=id;
while(dp[tx][ty] != )
{
int tmpx,tmpy;
tmpx = path[tx][ty].x;
tmpy = path[tx][ty].y;
if(dp[tx][ty] != dp[tmpx][tmpy])
{
save[cnt++]=t[ty];
}
tx = tmpx; ty = tmpy;
}
printf("%d\n",max);
for(i=cnt-; i>=; i--)
printf("%d ",save[i]);
printf("\n");
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,113
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,586
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,432
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922