HDU 1503 Advanced Fruits(最长公共子序列)
HDU OJ 终于又活过来了。
题目
The company "21st Century Fruits" has specialized in creating new sorts of fruits by transferring genes from one fruit into the genome of another one. Most times this method doesn't work, but sometimes, in very rare cases, a new fruit emerges that tastes like a mixture between both of them.
A big topic of discussion inside the company is "How should the new creations be called?" A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn't sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, "applear" contains "apple" and "pear" (APPLEar and apPlEAR), and there is no shorter string that has the same property.
A combination of a cranberry and a boysenberry would therefore be called a "boysecranberry" or a "craboysenberry", for example.
Your job is to write a program that computes such a shortest name for a combination of two given fruits. Your algorithm should be efficient, otherwise it is unlikely that it will execute in the alloted time for long fruit names.
思路
题目很长,但是主要意思是两个字符串合并(就是按顺序混合)的结果要是最短的。
因为题目要最短,所以两个字符串的最长公共子序列只出现一次就是最长的了。剩下的就是合并的时候,每个位置的字符都要按原位置合并。也就是说,在每个LCS中的字符之前的字符要按位置输出,这样就行了。
虽然LCS的状态转移方程有多个状态,但其实也可以直接写成一句,反而比较方便去理解了。
逆过程倒推LCS的话,要注意先考虑不匹配的情况,最后再考虑匹配的情况(也就是推导的那两个字符是一样的),否则会出问题(毕竟要和上面的求LCS过程倒过来嘛)。
代码
#include <bits/stdc++.h>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::string a, b;
while (std::cin >> a >> b) {
// 求LCS
std::vector< std::vector<int> > dp(a.size() + 1, std::vector<int>(b.size() + 1, 0));
for (int i = 0; i < a.size(); ++ i)
for (int j = 0; j < b.size(); ++ j)
dp[i + 1][j + 1] = std::max({dp[i][j] + (a[i] == b[j]), dp[i + 1][j], dp[i][j + 1]});
// 逆推求LCS字符在两个字符串之间的位置
// 使用大括号包起来,就是在一个局部作用域里面
std::vector< std::pair<int, int> > lcs;
{
int i = a.size(), j = b.size();
while (i > 0 && j > 0) {
if (dp[i][j] == dp[i - 1][j]) {
i --;
} else if (dp[i][j] == dp[i][j - 1]) {
j --;
} else {
i --;
j --;
lcs.push_back({i, j});
}
}
std::reverse(lcs.begin(), lcs.end());
}
// 输出结果
int i = 0, j = 0;
for (int id = 0; id < lcs.size(); ++ id) {
for (; i < lcs[id].first; ++ i)
std::cout << a[i];
for (; j < lcs[id].second; ++ j)
std::cout << b[j];
std::cout << a[lcs[id].first];
i = lcs[id].first + 1;
j = lcs[id].second + 1;
}
for (; i < a.size(); ++ i)
std::cout << a[i];
for (; j < b.size(); ++ j)
std::cout << b[j];
std::cout << '\n';
}
return 0;
}