hdu1501 Zipper

来源:互联网 发布:新型网络诈骗手段新闻 编辑:程序博客网 时间:2024/04/27 23:02
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<cstring>#include<iostream>using namespace std;char a[205],b[205],c[510];int vis[205][205],flag,la,lb,lc;void dfs(int i,int j,int k){    if(i==la&&j==lb&&k==lc){        flag = 1;return ;      //当三个字符串都到末尾时,flag=1 说明匹配    }    if(a[i]!=c[k]&&b[j]!=c[k]) //因为a,b是按顺便插入到c里        return ;               //串c的第k个字符,肯定与a,b的相对应的某个匹配,    if(vis[i][j]==1)return ;   //判断a的第i个字符与b的第j个字符是否与c比较过    vis[i][j] = 1 ;            //若没有则进行比较,并标记    if(a[i]==c[k]) dfs(i+1,j,k+1); //c[k]必定与a[i]/b[j]匹配    if(b[j]==c[k]) dfs(i,j+1,k+1);//若匹配,则相对应的进行下一个比较,同时k也加1}int main(){    int n;    scanf("%d",&n);    for(int i = 1 ; i <= n ; i++)    {        cin>>a>>b>>c;        la=strlen(a);lb=strlen(b);lc=strlen(c);        memset(vis,0,sizeof(vis));        flag=0;dfs(0,0,0);        printf("Data set %d: ",i);        if(flag)            printf("yes\n");        else            printf("no\n");    }    return 0;}

0 0
原创粉丝点击