for (int i = 1; i <= n; i ++ )
{
for (int j = 1; j <= n; j ++ )
{
f[i][j] = f[i - 1][j];
if (a[i] == b[j])
{
int maxv = 1;
for (int k = 1; k < j; k ++ )
if (a[i] > b[k])
maxv = max(maxv, f[i - 1][k] + 1);
f[i][j] = max(f[i][j], maxv);
}
}
}
作者:yxc
链接:https://www.acwing.com/solution/content/4955/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
将b[j] 换成 a[i] 后;
内层循环,如果a[i] > b[j] 就更新maxf 以备 j 之后的某个 b[p] == a[i] 的时候,就可以直接用。
#include <iostream>
#include <cstring>
using namespace std;
const int N = 3010;
int a[N], b[N], f[N][N];
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i ++) cin >> a[i];
for(int i = 1; i <= n; i ++) cin >> b[i];
for(int i = 1; i <= n; i ++)
{
int maxf = 1;
for(int j = 1; j <= n; j ++)
{
f[i][j] = f[i - 1][j];
if(a[i] == b [j]) f[i][j] = max(maxf, f[i][j]);
if(a[i] > b[j]) maxf = max(maxf, f[i - 1][j] + 1);
//cout << f[i][j] << endl;
}
}
int maxx= 0;
for(int i = 1; i <= n; i ++ ) maxx = max(maxx, f[n][i]);
cout << maxx;
return 0;
}