Zipper(HDU 1501) —— DFS

来源:互联网 发布:第一次登陆阿里云 编辑:程序博客网 时间:2024/05/21 15:48

Zipper

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6850    Accepted Submission(s): 2468


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
3cat tree tcraetecat tree catrteecat tree cttaree

Sample Output
Data set 1: yesData set 2: yesData set 3: no
题意:给你3个字符串,如果前面两个字符串随意按顺序挑选出字符来组成第三个字符串,则输出yes,否则输出no
 
写了半天才发现还是只能用dfs,开始没剪枝,结果TLE。所以应该用vis数组记录,以免发生计算重复的情况。这应该算是记忆化搜索了。
#include<stdio.h>#include<string.h>int vis[210][210], flag;char a[210], b[210], c[410];void DFS(int x, int y, int k){    if(c[k] == '\0') {flag = 1; return ;}    if(vis[x][y] || flag) return ;    vis[x][y] = 1; //vis数组记录是否已遍历过    if(a[x] == c[k]) DFS(x+1, y, k+1); //即使a数组的字符与c数组的字符相等也有可能不是正确的那个字符!    if(flag) return ;                      if(b[y] == c[k]) DFS(x, y+1, k+1);    return ;}int main(){    int T, t = 1;    scanf("%d", &T);    while(T--)    {        scanf("%s%s%s", a,b,c);        memset(vis, 0, sizeof(vis));        flag = 0; DFS(0,0,0);        printf("Data set %d: ", t++);        printf(flag ? "yes\n" : "no\n");    }    return 0;}

0 0