acm_最长相同子序列

本文介绍了一种寻找两个字符串中最长公共子序列的算法,并通过动态规划实现。该算法不仅适用于字符串,还可用于解决相似问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Problem Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = &lt;x1, x2, ..., xm&gt; another sequence Z = &lt;z1, z2, ..., zk&gt; is a subsequence of X if there exists a strictly increasing sequence &lt;i1, i2, ..., ik&gt; of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = &lt;a, b, f, c&gt; is a subsequence of X = &lt;a, b, c, f, b, c&gt; with index sequence &lt;1, 2, 4, 6&gt;. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y. <br>The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line. <br>
 

Sample Input
abcfbc abfcab programming contest abcd mnp
 

Sample Output
4 2 0
 

大意:输入两串字符串。。求他们的最长相同的子序列,不需要连续,但必须要有前后顺序,就比如abcfbc         abfcab  这两串最长的相同子序列是abcb或abfb,最大长度为4。。


思路:a[i]代表第一串字符串的第i+1个字符

               同理b[i]。。

              c[i][j]代表第一串的前i个字符和第二串的前j个字符最长的相同子序列

             动态规划方程:

             if(a[i-1] == b[j-1])
                    c[i][j] = c[i-1][j-1] + 1;
                else if(c[i][j-1] >= c[i-1][j])
                    c[i][j] = c[i][j-1];
                else
                    c[i][j] = c[i-1][j];


代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int main()
{
//freopen("r.txt","r",stdin);
    string s;
    string t;
int i;
    while(cin>>s>>t)
    {
        const char* a = s.c_str();
        const char* b = t.c_str();
        int m = strlen(a) + 1;
        int n = strlen(b) + 1;
        int** c = new int*[m];
        for(i = 0; i < m; i++)
            c[i] = new int[n];
        for(i = 0; i < m; i++)
            c[i][0] = 0;
        for(i = 0; i < n; i++)
            c[0][i] = 0;
        for(i = 1; i < m; i++)
            for(int j = 1; j < n; j++)
            {
                if(a[i-1] == b[j-1])
                    c[i][j] = c[i-1][j-1] + 1;
                else if(c[i][j-1] >= c[i-1][j])
                    c[i][j] = c[i][j-1];
                else
                    c[i][j] = c[i-1][j];
            }
        cout<<c[m-1][n-1]<<endl;       
    }
    return 0;
}


感想:。。。。。好难啊。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值