题目链接:HDU 1501
Description
Given three strings, you are to determine whether the third string can be formed by combining the characters in the first two strings. The first two strings can be mixed arbitrarily, but each must stay in its original order.
For example, consider forming "tcraete" from "cat" and "tree":
String A: cat
String B: tree
String C: tcraete
As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming "catrtee" from "cat" and "tree":
String A: cat
String B: tree
String C: catrtee
Finally, notice that it is impossible to form "cttaree" from "cat" and "tree".
Input
The first line of input contains a single positive integer from 1 through 1000. It represents the number of data sets to follow. The processing for each data set is identical. The data sets appear on the following lines, one data set per line.
For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two strings will have lengths between 1 and 200 characters, inclusive.
Output
For each data set, print:
Data set n: yes
if the third string can be formed from the first two, or
Data set n: no
if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.
Sample Input
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Sample Output
Data set 1: yes
Data set 2: yes
Data set 3: no
题意
给定3个字符串,问在不改变前两个字符串内字母的相对位置的前提下能否组成第3个字符串,保证前两个字符串长度之和等于第三个字符串。
题解:
这道题的解法有多种,有说用DP的,有说用最短路的、、、无奈我只会DFS,最后用DFS跑出来的这道题,而且思路也比较简单。
设置一个标记,表示匹配到了第3个字符串的第几个字母,在DFS时,只要有一个字母被跳过了,那就说明肯定无解,因为:保证前两个字符串长度之和等于第三个字符串,在输入时加了一个对字母组成的剪枝,刚开始超时就卡在这个判断上了。
代码
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
char a[210], b[210], g[450];
int cur1, cur2;
bool dfs(int temp) {
if (temp == strlen(g))
{
return true;
}
if (a[cur1] == g[temp]) {
cur1++;
if(dfs(temp + 1))
return true;
cur1--;
}
if (b[cur2] == g[temp]) {
cur2++;
if(dfs(temp + 1))
return true;
cur2--;
}
return false;
}
int main() {
int Case = 1;
int t;
scanf("%d", &t);
map<char, int>P1;
map<char, int>P2;
while (t--) {
P1.clear();
P2.clear();
cur1 = cur2 = 0;
scanf("%s%s%s", a, b, g);
for (int i(0); i < strlen(a); i++)
P1[a[i]]++;
for (int i(0); i < strlen(b); i++)
P1[b[i]]++;
for (int i(0); i < strlen(g); i++)
P2[g[i]]++;
if (P1 != P2) {
printf("Data set %d: no
", Case++);
}
else {
if (!dfs(0)) {
printf("Data set %d: no
", Case++);
}
else printf("Data set %d: yes
", Case++);
}
}
return 0;
}