题目描述:
Problem Description 小明和他的好朋友小西在玩一个新的游戏,由小西给出一个由小写字母构成的字符串,小明给出另一个比小西更长的字符串,也由小写字母组成,如果能通过魔法转换使小明的串和小西的变成同一个,那么他们两个人都会很开心。这里魔法指的是小明的串可以任意删掉某个字符,或者把某些字符对照字符变化表变化。如: Input 首先输入T,表示总共有T组测试数据(T <= 40)。
Output 对于每组数据,先输出Case数。
Sample Input
Sample Output
|
思路: dp[i][j] = true 代表小明的前 j 个字符可以 转换成前 小西 前 i 个字符。
dp[i][j] 为 true 的 三种情况:
1. 小明前 j - 1 个字符 已经可以转换成 小西 前 i 字符 , 那么 前 j 个 肯定也行。
2.小明 第 j 个字符 等于 小西 第 i 个 字符, 且 dp[i-1][j-1] 为 true.
3.小明 第 j 个字符 可以以通过转换 等于 小西 第 i 个 字符
参考代码:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010;
// 如果 judge[i][j] == true, 则 'a'+i 可转化成为 'a'+j
bool judge[30][30];
// 如果 dp[i][j] == true, 则代表小明的前 j 个字符可以 转换成前 小西 前 i 个字符
bool dp[N][N];
int main() {
int T, m;
// ch 小西的字符串, sh 小明的字符串
string ch, sh;
cin >> T;
for(int t=1; t<=T; t++) {
cin >> ch >> sh >> m;
// 字符串的下标从 1 开始
ch = "#"+ch;
sh = "#"+sh;
memset(judge, 0, sizeof(judge));
char a, b;
for(int i=1; i<=m; i++) {
cin >> a >> b;
judge[b-'a'][a-'a'] = true;
}
int chLength = ch.length();
int shLength = sh.length();
memset(dp, 0, sizeof(dp));
for(int i=0; i<shLength; i++) {
dp[0][i] = true;
}
for(int i=1; i<=chLength; i++) {
for(int j=1; j<=shLength; j++) {
if(true == dp[i][j-1]) {
dp[i][j] = true;
continue;
}
if(((ch[i] == sh[j]) || judge[ch[i]-'a'][sh[j]-'a']) && dp[i-1][j-1]) {
dp[i][j] = true;
continue;
}
}
}
if(true == dp[chLength][shLength]) {
cout << "Case #" << t << ": happy" << endl;
}
else {
cout << "Case #" << t << ": unhappy" << endl;
}
}
return 0;
}