注释的是我自己写的记录路径 WA 想不通
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>
#include<iomanip>
using namespace std;
#define MAX(a,b) (a>b?a:b)
typedef long long LL;
int dp[555][555];
int a[555],b[555];
int n,m;
/* //一直WA
struct
{
int x,y;
}
road[555][555];
int f;
int ans;
void dfs(int x,int y)
{
if(x==0)
return;
dfs(road[x][y].x,road[x][y].y);
if(a[x]==b[y])
{
f++;
if(f==ans)
cout<<a[x]<<endl;
else
cout<<a[x]<<' ';
}
}
void lcis()
{
memset(dp,0,sizeof(dp));
memset(road,0,sizeof(road));
for(int i=1;i<=n;i++)
{
int max=0;
int y=0;
for(int j=1;j<=m;j++)
{
if(b[j]<a[i])
{
if(max<dp[i-1][j])
{
max=dp[i-1][j];
y=j;
}
}
if(a[i]==b[j])
{
dp[i][j]=max+1;
road[i][j].x=i-1;
road[i][j].y=y;
}
else
{
dp[i][j]=dp[i-1][j];
road[i][j].x=i-1;
road[i][j].y=j;
}
}
}
ans=0;
int pos;
for(int i=1;i<=m;i++)
{
if(ans<dp[n][i])
{
ans=dp[n][i];
pos=i;
}
}
cout<<ans<<endl;
if(ans)
{
f=0;
dfs(n,pos);
}
}
*/
int road[555][555];
int f;
int ans;
void dfs(int x,int y)
{
if(x==0||y==0)
return;
if(a[x]==b[y])
{
dfs(x-1,road[x][y]);
f++;
if(f==ans)
cout<<a[x]<<endl;
else
cout<<a[x]<<' ';
}
else
dfs(x-1,y);
}
void lcis()
{
ans=0;
int x,y;
memset(dp,0,sizeof(dp));
memset(road,0,sizeof(road));
for(int i=1;i<=n;i++)
{
int max=0;
int k=0;
for(int j=1;j<=m;j++)
{
if(b[j]<a[i])
{
if(max<dp[i-1][j])
{
max=dp[i-1][j];
k=j;
}
}
if(a[i]==b[j])
{
dp[i][j]=max+1;
road[i][j]=k;
}
else
dp[i][j]=dp[i-1][j];
if(ans<dp[i][j])
{
ans=dp[i][j];
x=i;
y=j;
}
}
}
cout<<ans<<endl;
if(ans)
{
f=0;
dfs(x,y);
}
}
int main()
{
while(cin>>n)
{
for(int i=1;i<=n;i++)
cin>>a[i];
cin>>m;
for(int i=1;i<=m;i++)
cin>>b[i];
lcis();
// system("pause");
}
return 0;
}