加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++最长公共子序列

发布时间:2020-12-16 09:14:29 所属栏目:百科 来源:网络整理
导读:最长公共子序列 Description Input 第一行:序列A的长度 第二行:给出序列A 第三行:序列B的长度 第四行:给出序列B 长度=1000 Output 只有一行:表示最长的公共子序列的长度 Sample Input 61 6 2 5 4 770 1 2 5 5 2 7 Sample Output 4 Source #include bits

最长公共子序列

Description

Input

第一行:序列A的长度 第二行:给出序列A 第三行:序列B的长度 第四行:给出序列B

长度<=1000

Output

只有一行:表示最长的公共子序列的长度

Sample Input

6
1 6 2 5 4 7
7
0 1 2 5 5 2 7

Sample Output

4

Source

#include <bits/stdc++.h>
using namespace std;
int f[1001][1001];
int n,m,a[1001],b[1001];
int main()
{
    cin >> n;
    for(int i = 1;i <= n;i ++) {
        scanf("%d",&a[i]);
    }
    cin >> m;
    for(int i = 1;i <= m;i ++) {
        scanf("%d",&b[i]);
    }
    f[0][0] = 0;
    f[0][1] = 0;
    f[1][0] = 0;
    for(int i = 1;i <= n;i ++) {
        for(int j = 1;j <= m;j ++) {
            if(a[i] == b[j]) {
                f[i][j] = f[i - 1][j - 1] + 1;
            }
            else {
                f[i][j] = max(f[i - 1][j],f[i][j - 1]);
            }
        }
    }
    cout << f[n][m] << endl;
    return 0; 
}
/**************************************************************
    Problem: 1602
    User: LJA001162
    Language: C++
    Result: 正确
    Time:4 ms
    Memory:5460 kb
****************************************************************/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读