Zipper 递归

来源:互联网 发布:网络币骗局 编辑:程序博客网 时间:2024/06/05 05:18


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.
样例输入
3cat tree tcraetecat tree catrteecat tree cttaree
样例输出
Data set 1: yesData 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 0
原创粉丝点击