首页 > 其他 > 详细

HDU 1501 Zipper (DFS)

时间:2015-03-25 21:38:39      阅读:224      评论:0      收藏:0      [点我收藏+]
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

题意:给你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);
        else
            printf("Data set %d: no\n",j);
    }
    return 0;
}


HDU 1501 Zipper (DFS)

原文:http://blog.csdn.net/u012313382/article/details/44626529

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!