HDU 1501 Zipper (记忆化搜索)

题面

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

思路

给你三个字符串,问你最后一个串能不能根据前面的串组合得到,前面的串可以随意切割,但是不得改变原串顺序。我们根据样例来演算一下,首先目标的第一个字符如果和前两个串的第一个字符都不相等,那么这个字符串肯定不可能被拼起来。因为每个串的字符在目标串的顺序是不会成逆的,所以每当匹配了之后我们将被匹配的字符串的类似于指针的东西后移一位,一直重复,如果最后可以搜到前两个串的最后两位,那么这个串是成立的。因为这里会有大量重复,所以我们写一个记忆化搜索。

代码实现

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
#define eps 1e-4
const int maxn=10005;
const int N = 60;
int t,k;
bool flag;
int vis[205][205];
string str1,str2,str;
void dfs (int s1,int s2,int s) {
   if (s1==str1.length()&&s2==str2.length()) {
      flag=true;
      return ;
   }
   if (str1[s1]!=str[s]&&str[s2]!=str[s2]) return ;
   if (vis[s1][s2]) return ;
   vis[s1][s2]=1;
   if (str1[s1]==str[s]) dfs (s1+1,s2,s+1);
   if (str2[s2]==str[s]) dfs (s1,s2+1,s+1);

}
int main () {
   cin>>t;
   while (t--) {
     cin>>str1>>str2>>str;
     flag = false;
     memset  (vis,0,sizeof (vis));
     dfs (0,0,0);
     cout<<"Data set "<<++k<<": ";
     if (flag) cout<<"yes"<<endl;
     else cout<<"no"<<endl;
   }
    return 0;
}
原文地址:https://www.cnblogs.com/hhlya/p/13149786.html