Description
You are given two words (each word consists of upper-case English letters).
Try to delete some letters from each word so that the resulting words are equal.
What is the maximum possible length of the resulting word?
Try to delete some letters from each word so that the resulting words are equal.
What is the maximum possible length of the resulting word?
Input
There will be no more than 10 test cases.
Each test case consists of a single line, contaning the two words separated by a single space. The length of each of these words is between 1 and 200.
Each test case consists of a single line, contaning the two words separated by a single space. The length of each of these words is between 1 and 200.
Output
For each test case output the maximum length of a resulting word (the length of the longest word that can be created from both words by removing some letters).
If the two words have no letters in common, output 0.
If the two words have no letters in common, output 0.
Sample Input
AAABBB ABABAB AXYAAZ CCCXCCCYCCCZCC ABCDE EDCBA
Sample Output
4 31
根据题目的意思,可以看出其实就是求最长公共子序列,然后dp一下即可
#include<set> #include<map> #include<ctime> #include<cmath> #include<stack> #include<queue> #include<bitset> #include<cstdio> #include<string> #include<cstring> #include<iostream> #include<algorithm> #include<functional> #define rep(i,j,k) for (int i = j; i <= k; i++) #define per(i,j,k) for (int i = j; i >= k; i--) using namespace std; typedef long long LL; const int low(int x) { return x&-x; } const double eps = 1e-8; const int INF = 0x7FFFFFFF; const int mod = 1e9 + 7; const int N = 1e3 + 10; int T, f[N][N]; char a[N], b[N]; int main() { while (scanf("%s%s", a + 1, b + 1) != EOF) { f[0][0] = 0; for (int i = 1; a[i]; i++) { for (int j = 1; b[j]; j++) { if (a[i] == b[j]) f[i][j] = f[i - 1][j - 1] + 1; else f[i][j] = max(f[i][j - 1], f[i - 1][j]); } } printf("%d\n", f[strlen(a + 1)][strlen(b + 1)]); } return 0; }