Virus |
We have a log file, which is a sequence of recorded events. Naturally, the timestamps are strictly increasing.
However, it is infected by a virus, so random records are inserted (but the order of original events is preserved). The backup log file is also infected, but since the virus is making changes randomly, the two logs are now different.
Given the two infected logs, your task is to find the longest possible original log file. Note that there might be duplicated timestamps in an infected log, but the original log file will not have duplicated timestamps.
Input
The first line contains T ( T100), the number of test cases. Each of the following lines contains two lines, describing the two logs in the same format. Each log starts with an integer n ( 1n1000), the number of events in the log, which is followed by n positive integers not greater than 100,000, the timestamps of the events, in the same order as they appear in the log.
Output
For each test case, print the number of events in the longest possible original log file.
Sample Input
1 9 1 4 2 6 3 8 5 9 1 6 2 7 6 3 5 1
Sample Output
3
题目大意:T种情况,每种情况2行数据,每行数据第一个表示个数,接下来是一个序列,问两组数据的最长公共递增子序列的长度。
解题思路:当看到这题想到的是LCS和LIS问题,没错这题也是动态规划问题,只要找到状态转移方程就可轻易搞定!
>_<:LIS设DP[i]表示以第i个数字结尾的最长上升子序列的长度
>0<:DP[i]=max(DP[j]+1){1<=j<=i-1}
>_<:LCS设DP[i][j]表示以A串第i个字符结尾以B串第j个字符结尾的最长字串
>0<:当a[i]==b[j]时:DP[i][j]=DP{i-1][j-1]+1;
当a[i]!=b[j]时:DP[i][j]=max(DP[i-1][j],DP[i][j-1])
>_<:LCIS设F[i][j]表示以a串前i个字符b串的前j个字符且以b[j]为结尾构成的LCIS的长度
>0<:当a[i]!=b[j]时:F[i][j]=F[i-1][j]
当a[i]==b[j]时:F[i][j]=max(F[i-1][k])+1 1<=k<=j-1 && b[j]>b[k]
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<string.h> 5 #include<cstring> 6 #include<cmath> 7 #include<sstream> 8 #include<iomanip> 9 #include<algorithm> 10 #include<vector> 11 using namespace std; 12 int f[1005][1005],a[1005],b[1005],i,j,t,n1,n2,maxn; 13 int main() 14 { 15 scanf("%d",&t); 16 while(t--) 17 { 18 scanf("%d",&n1); 19 for(i=1;i<=n1;i++) scanf("%d",&a[i]); 20 scanf("%d",&n2); 21 for(i=1;i<=n2;i++) scanf("%d",&b[i]); 22 memset(f,0,sizeof(f)); 23 for(i=1;i<=n1;i++) 24 { 25 maxn=0; 26 for(j=1;j<=n2;j++) 27 { 28 f[i][j]=f[i-1][j];//不相等 29 if (a[i]>b[j]&&maxn<f[i-1][j]) maxn=f[i-1][j];//更新maxn 30 if (a[i]==b[j]) f[i][j]=maxn+1;//相等 31 } 32 } 33 maxn=0; 34 for(i=1;i<=n2;i++)if(maxn<f[n1][i])maxn=f[n1][i]; 35 printf("%d ",maxn); 36 } 37 return 0; 38 }