题目:
http://poj.org/problem?id=1934
https://www.acwing.com/problem/content/317/
题意:
爱丽丝和鲍勃想去旅行。
他们每个人制定了一条旅行路线,每条路线包含一个按给定顺序访问的城市列表,一个城市可能会多次出现在同一路线中。
因为他们想要一起去旅行,所以必须在旅行路线上达成一致。
他们两个都不想改变他们的路线上的城市顺序或者在路线上额外添加城市。
因此,他们只能移除各自路线中的一些城市,使得旅行路线达成一致,并且尽可能的长。
该地区共有26个城市,用小写字母’a’到’z’表示。
输入格式
输入包含两行,第一行是爱丽丝的路线城市列表,第二行是鲍勃的路线城市列表。
每个列表由1到80个小写字母组成,其间没有空格。
输出格式
按升序顺序输出所有满足条件的路线列表。
每个路线列表占一行。
代码有注释~
#include<iostream>
#include<cmath>
#include<algorithm>
#include<stdio.h>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#define ll long long
#define ull unsigned long long
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 88;
int dp[maxn][maxn];
int num1[maxn], num2[maxn], len1, len2;
//pos1 && pos2 用于存字母的位置 pos1[i][j]表示在下标为i的位置
// 字母j+'a' (因为j是正数,j+'a'就表示字母了)上一次在序列中出现的下标
int pos1[maxn][30], pos2[maxn][30];
set<string> S; //S用于存储答案以及去重
char res[maxn]; //res辅助存储答案,用来临时存储答案
void solve(int now_len1, int now_len2, int now_len) {
if (now_len == 0) {//now_len=0表示成功找到一串序列
string s = res + 1;
S.insert(s);
}
else if (now_len1&&now_len2) {
//遍历26个字母,分别试一下可不可以用这个字母来作为答案序列
for (int i = 0; i < 26; i++) {
int to1 = pos1[now_len1][i], to2 = pos2[now_len2][i];
if(dp[to1][to2]==now_len){
//试一下可否作为答案序列
res[now_len] = (char)(i + 'a');
solve(to1 - 1, to2 - 1, now_len - 1);
}
}
}
}
int main() {
char s[maxn];
scanf("%s", s + 1);
len1 = strlen(s + 1);
for (int i = 1; i <= len1; i++)
num1[i] = s[i] - 'a';
scanf("%s", s + 1);
len2 = strlen(s + 1);
for (int i = 1; i <= len2; i++)
num2[i] = s[i] - 'a';
//dp求最长公共子序列
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (num1[i] == num2[j])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
//预处理pos
for (int i = 1; i <= len1; i++) {
for (int j = 0; j < 26; j++) {
if (num1[i] == j)
pos1[i][j] = i;
else
pos1[i][j] = pos1[i - 1][j];
}
}
for (int i = 1; i <= len2; i++) {
for (int j = 0; j < 26; j++) {
if (num2[i] == j)
pos2[i][j] = i;
else
pos2[i][j] = pos2[i - 1][j];
}
}
solve(len1, len2, dp[len1][len2]);
//输出答案
set<string>::iterator it;
for (it = S.begin(); it != S.end(); it++)
cout << *it << endl;
return 0;
}