dp最长公共子序列
给定两个长度分别为N和M的字符串A和B,求既是A的子序列又是B的子序列的字符串长度最长是多少。
输入格式
第一行包含两个整数N和M。
第二行包含一个长度为N的字符串,表示字符串A。
第三行包含一个长度为M的字符串,表示字符串B。
字符串均由小写字母构成。
输出格式
输出一个整数,表示最大长度。
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int dp[1010][1010];
char s1[1010];
char s2[1010];
int main(){
//ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
//f[i][j]指的是长度为i的A串和长度为j的B串的最长公共子序列长度
//如果两个字符相等,就可以直接转移到f[i-1][j-1],不相等的话,两个字符一定有一个可以抛弃,可以对f[i-1][j],f[i][j-1]两种状态取max来转移。
int n,m;
cin>>n>>m;
cin>>s1+1>>s2+1;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; 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[n][m]<<endl;
}
改编题
codeforces div2 D:https://codeforces.com/contest/1447/problem/D
-
D. Catching Cheaters time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard output You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅LCS(C,D)−|C|−|D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C,D) over all pairs (C,D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the Wikipedia page about the Longest Common Subsequence problem. Input The first line contains two positive integers n and m (1≤n,m≤5000) — lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters — string A. The third line contains a string consisting of m lowercase Latin letters — string B. Output Output maximal S(C,D) over all pairs (C,D), where C is some substring of A, and D is some substring of B.
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
ll dp[5010][5010];
char s1[5010];
char s2[5010];
int main(){
//ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
ll n,m;
cin>>n>>m;
cin>>s1+1>>s2+1;
ll mx = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1[i] == s2[j]) dp[i][j] = dp[i-1][j-1] + 2;
else dp[i][j] = max(dp[i-1][j]-1,dp[i][j-1]-1);
dp[i][j] = max(dp[i][j],0LL);
mx = max(mx,dp[i][j]);
}
}
cout<<mx<<endl;
}

浙公网安备 33010602011771号