Zipper
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 15 Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem 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
这道题一开始以为是记忆化搜索,后来发现是一道很水的搜索题,他说了按顺序,那么我设计一个标记把s_1 ,s_2所有排列组合的情况放在一个数组里面,如果我这个出现过那么不搜了停止,知道c == s3.size()就可以了。很水的一道搜索题
# include <iostream>
# include <cstring>
# include <string>
# include <cstdio>
using namespace std;
int n;
const int maxn = 250;
bool flag;
string s1, s2, s3;
bool book[maxn][maxn];
void dfs(int c, int s_1, int s_2)
{
if(c == s3.size() && s_1 == s1.size() && s_2 == s2.size())
{
flag = true;
return ;
}
if(flag)
{
return ;
}
if(book[s_1][s_2])
{
return ;
}
if(s3[c] != s1[s_1] && s3[c] != s2[s_2])
{
return ;
}
book[s_1][s_2] = true;
if(s3[c] == s1[s_1])
{
dfs(c + 1, s_1 + 1, s_2);
}
if(s3[c] == s2[s_2])
{
dfs(c + 1, s_1, s_2 +1);
}
return ;
}
int main(int argc, char *argv[])
{
ios::sync_with_stdio(false);
while(cin >> n)
{
for(int i = 1; i <= n; i++)
{
cin >> s1 >> s2 >> s3;
flag = false;
memset(book, false, sizeof(book));
cout << "Data set "<< i <<": ";
dfs(0, 0, 0);
if(flag)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
}
}
return 0;
}