Acwing 272.最长公共上升子序列 (DP)

题面

熊大妈的奶牛在小沐沐的熏陶下开始研究信息题目。

小沐沐先让奶牛研究了最长上升子序列,再让他们研究了最长公共子序列,现在又让他们研究最长公共上升子序列了。

小沐沐说,对于两个数列A和B,如果它们都包含一段位置不一定连续的数,且数值是严格递增的,那么称这一段数是两个数列的公共上升子序列,而所有的公共上升子序列中最长的就是最长公共上升子序列了。

奶牛半懂不懂,小沐沐要你来告诉奶牛什么是最长公共上升子序列。

不过,只要告诉奶牛它的长度就可以了。

数列A和B的长度均不超过3000。

输入格式
第一行包含一个整数N,表示数列A,B的长度。

第二行包含N个整数,表示数列A。

第三行包含N个整数,表示数列B。

输出格式
输出一个整数,表示最长公共上升子序列的长度。

数据范围
1≤N≤3000,序列中的数字均不超过231−1
输入样例:
4
2 2 1 3
2 1 2 3
输出样例:
2

思路

经典动规,我们考虑f[i][j]为以a[i],b[j]构成匹配状态的且以b[j]结尾最长序列数,然后根据最后各自两个点是否相等进行状态转移就可以了。

代码实现

#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define rep(i,f_start,f_end) for (int i=f_start;i<=f_end;++i)
#define per(i,n,a) for (int i=n;i>=a;i--)
#define MT(x,i) memset(x,i,sizeof(x) )
#define rev(i,start,end) for (int i=0;i<end;i++)
#define inf 0x3f3f3f3f
#define mp(x,y) make_pair(x,y)
#define lowbit(x) (x&-x)
#define MOD 1000000007
#define exp 1e-8
#define N 1000005 
#define fi first 
#define se second
#define pb push_back
typedef long long ll;
typedef pair<int ,int> PII;
ll gcd (ll a,ll b) {return b?gcd (b,a%b):a; }
inline int read() {
    char ch=getchar(); int x=0, f=1;
    while(ch<'0'||ch>'9') {
        if(ch=='-') f = -1;
        ch=getchar();
    } 
    while('0'<=ch&&ch<='9') {
        x=x*10+ch-'0';
        ch=getchar();
    }   return x*f;
}
const int maxn=3010;
int f[maxn][maxn];
int a[maxn];
int b[maxn];
int n;


int main () {
   cin>>n;
  rep (i,1,n) cin>>a[i];
  rep (i,1,n) cin>>b[i];

  rep (i,1,n) {
      int maxv=1;
      rep (j,1,n) {
          f[i][j]=f[i-1][j];
          if (a[i]==b[j]) f[i][j]=max (maxv,f[i][j]);
          if (b[j]<a[i]) maxv=max (maxv,f[i-1][j]+1);
      }
  }
  int  res=0;
  rep (i,1,n) {
      res= max (res,f[n][i]);
  }
  cout<<res<<endl;
   
    return 0;
}
原文地址:https://www.cnblogs.com/hhlya/p/13423725.html