HDU 1501 Zipper (DFS)

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: catString B: treeString C: tcraeteAs 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: catString B: treeString C: catrteeFinally, 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: yesif the third string can be formed from the first two, orData set n: noif 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个单词,要你判断第三个单词是否由前2个单词以任意的排列(这2个单词的顺序不能改变)组合而成

思路:数据太小了,直接DFS吧!用a,,b分别表示2个单词出现到了哪个字母,如果最终能出现完这2个单词,那么说明是满足条件的

AC代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;char str1[205];char str2[205];char str[405];int vis[205][205];int len1,len2,len;int flag;void dfs(int a,int b,int l){if(vis[a][b])return ;if(a==len1&&b==len2){flag=1;}if(flag==1)return ;vis[a][b]=1;if(str[l]==str1[a]&&a<len1){a++;dfs(a,b,l+1);a–;}if(str[l]==str2[b]&&b<len2){b++;dfs(a,b,l+1);}}int main(){int t;scanf("%d",&t);for(int j=1;j<=t;j++){getchar();scanf("%s%s%s",str1,str2,str);memset(vis,0,sizeof(vis));int i;flag=0;len1=strlen(str1);len2=strlen(str2);dfs(0,0,0);if(flag)printf("Data set %d: yes\n",j);elseprintf("Data set %d: no\n",j);}return 0;}

一个人骑行,孤单却内省;一群人骑行,壮观而有力。

HDU 1501 Zipper (DFS)

相关文章:

你感兴趣的文章:

标签云: