Zipper 遞歸


Zipper




  • 查看

  • 提交

  • 統計

  • 提問




總時間限制: 

1000ms 

內存限制: 

65536kB




描述

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".



輸入

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.



輸出

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.



樣例輸入


3
cat tree tcraete
cat tree catrtee
cat tree cttaree



樣例輸出


Data set 1: yes
Data set 2: yes



遞歸方法實現,結果正確,但是超時


應該用動態規劃實現,以空間換時間,以後修改瞭會貼在下面


#include<iostream>

#include<cstring>

#include<stdio.h>

#include<vector>

using namespace std;


string stra;

string strb;

string strc;

char str[1000];

bool flag=false;


int strlen(string s){

int i=0;

while(s[i]!='\0'){

++i;



return i;

}


void Zipper(int x,int n,int a,int b){

if(flag)return ;

if(x==n){

if(str==strc){

flag=true;

}

return ;

}


if(stra[a]==strc[x]){

str[x]=stra[a];

Zipper(x+1,n,a+1,b);

}

if(strb[b]==strc[x]){

str[x]=strb[b];

Zipper(x+1,n,a,b+1);

}else{

return ;

}

}


int main(){

int count;

cin>>count;

vector<bool>v;

for(int i=0;i<count;++i){

cin>>stra>>strb>>strc;

int n;

n=strlen(strc);

Zipper(0,n,0,0);


v.push_back(flag);

flag=false;

}


for(int i=0;i<count;++i){

if(v[i]){

printf("Data set %d : yes",(1+i));

//cout<<"Data set "<<1+i<<" : yes"<<endl;

}else{

printf("Data set %d : no",(1+i));

//cout<<"Data set "<<i+1<<" : no"<<endl;

}

}


return 0;

}

0 個評論

要回覆文章請先登錄註冊