# POJ 2192 && HDU 1501 Zipper (记忆化搜索)

679人阅读 评论(0)

Zipper
 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 16803 Accepted: 5994

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


Source

Pacific Northwest 2004

#include <cstdio>
#include <cstring>
int const MAX = 1005;
char s1[MAX], s2[MAX], s3[MAX];
bool dp[MAX][MAX];
bool flag;

void DFS(int i1, int i2, int i3)
{
if(flag || i3 == (int)strlen(s3))
{
flag = true;
return;
}
if(dp[i1][i2])
return;
dp[i1][i2] = true;
if(s1[i1] == s3[i3])
DFS(i1 + 1, i2, i3 + 1);
if(s2[i2] == s3[i3])
DFS(i1, i2 + 1, i3 + 1);
return;
}

int main()
{
int T, ca = 1;
scanf("%d", &T);
while(T--)
{
memset(dp, false, sizeof(dp));
flag = false;
scanf("%s %s %s", s1, s2, s3);
DFS(0, 0, 0);
if(flag)
printf("Data set %d: yes\n", ca ++);
else
printf("Data set %d: no\n", ca ++);
}
}

个人资料
等级：
访问量： 75万+
积分： 1万+
排名： 865
博客专栏
 算法题 文章：50篇 阅读：35173 Java学习笔记 文章：10篇 阅读：11930 LeetCode 文章：138篇 阅读：80074