作者:痛彻心扉哥哥_742 | 来源:互联网 | 2023-02-03 15:20
算是LCIS的入门题吧,这个dp方法以前没怎么看,现在好好地学习了下,dp真的是奥妙无穷首先,dp的最开始是定义状态dp[i][j]表示A串的前i个,与B串的前j个,并以B[j]为结尾
算是LCIS的入门题吧, 这个dp方法以前没怎么看,现在好好地学习了下,dp真的是奥妙无穷...
首先,dp的最开始是定义状态 dp[i][j] 表示A串的前i个,与B串的前j个,并以B[j]为结尾的LCIS 的长度.
状态转移方程:
if(A[i]==B[j]) dp[i][j]=max(dp[i-1][k])+1; ( 1 <= k
else dp[i][j]=dp[i-1][j];
然后选择循环顺序,就可以将算法的复杂度降为n*n.
Greatest Common Increasing Subsequence
Time Limit: 2 Seconds
Memory Limit: 65536 KB
Special Judge
You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal
possible length.
Sequence S1, S2, ..., SN of length N is called an increasing subsequence of a sequence A1, A2, ..., AM of length M if there exist 1 <= i1
Input
Each sequence is described with M - its length (1 <= M <= 500) and M integer numbers Ai (-2^31 <= Ai <2^31) - the sequence itself.
Output
On the first line of the output print L - the length of the greatest common increasing subsequence of both sequences. On the second line print the subsequence itself. If there are several possible answers, output any of them.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Sample Input
1
5
1 4 2 5 -12
4
-12 1 2 4
Sample Output
2
1 4
Source: Northeastern Europe 2003, Northern Subregion
#include
#include <string.h>
#include
using namespace std;
#define N 550
struct node
{
int x,y;
}path[N][N];
int dp[N][N];
int s[N],t[N];
int main()
{
int t1;
while(scanf("%d",&t1)!=EOF)
{
while(t1--)
{
memset(path,0,sizeof(path));
int n,m;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&s[i]);
scanf("%d",&m);
for(int i=1;i<=m;i++)
scanf("%d",&t[i]);
memset(dp,0,sizeof(dp));
int mx=0;
for(int i=1;i<=n;i++)
{
mx=0;
int tx=0,ty=0;
for(int j=1;j<=m;j++)
{
dp[i][j] = dp[i-1][j];
path[i][j].x=i-1;
path[i][j].y=j;
if( s[i]>t[j] && mx1][j])
{
mx=dp[i-1][j];
tx=i-1;
ty=j;
}
if( s[i] == t[j] )
{
dp[i][j]=mx+1;
path[i][j].x=tx;
path[i][j].y=ty;
}
}
}
mx=-1;
int id;
for(int i=1;i<=m;i++)
if(dp[n][i]>mx)
{
mx=dp[n][i];
id=i;
}
int save[N];
int cnt=0;
int tx,ty;
tx=n; ty=id;
while( dp[tx][ty] != 0 )
{
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",mx);
for(int i=cnt-1;i>=0;i--)
printf("%d ",save[i]);
printf("\n");
}
}
return 0;
}