考研机试真题--Coincidence--上海交通大学

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Void_worker/article/details/81906602

关键字:最长公共子序列

题目描述
Find a longest common subsequence of two strings.
输入描述:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出描述:
For each case, output k – the length of a longest common subsequence in one line.
示例1
输入
abcd
cxbydz
输出
2

链接:
https://www.nowcoder.com/practice/f38fc44b43cf44eaa1de407430b85e69?tpId=40&tqId=21445&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

思路:
状态设计:dp[i][j] 为s1前i,s2前j个时最长的公共子序列
状态转移方程:
if(s1[i] == s2[j]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);

代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = 110;
char s1[maxn], s2[maxn];
int dp[maxn][maxn];

int main(){
//    freopen("a.txt", "r", stdin);
    int len1, len2;
    while(gets(s1 + 1)){   //从下标为1时开始读入
        gets(s2 + 1);
        len1 = strlen(s1 + 1);
        len2 = strlen(s2 + 1);
//        puts(s1 + 1);
//        puts(s2 + 1);
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= len1; ++i){
            for(int j = 1; j <= len2; ++j){
                if(s1[i] == s2[j]) dp[i][j] = dp[i - 1][j - 1] + 1;
                else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
        printf("%d\n", dp[len1][len2]);
    }
    return 0;
}

错误代码:
下标没处理好…
下标以0开始,如果s1[0] == s2[0]的话,那么dp[0][0]应该为1,而不是初始化为0

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;

int main(){
//    freopen("a.txt", "r", stdin);
    string s1, s2;
    int len1, len2, dp[110][110];
    while(cin >> s1 >> s2){
        len1 = s1.length();
        len2 = s2.length();
        for(int i = 0; i < len1; ++i){
            dp[i][0]= 0;
        }
        for(int j = 0; j < len2; ++j){
            dp[0][j] = 0;
        }
        for(int i = 1; i < len1; ++i){
            for(int j = 1; j < len2; ++j){
                if(s1[i] == s2[j]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                else{
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        cout << dp[len1 - 1][len2 - 1] << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/Void_worker/article/details/81906602