Zipper

来源:互联网 发布:csol2淘宝刷枪 编辑:程序博客网 时间:2024/05/21 10:26

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
Source
Pacific Northwest 2004
题解
给你三个字符串abc,请你判断字符串c是不是由字符串ab混合而成,但有一个限制,字符串ab在c的存在位置必须要顺序,比如”cttaree” from “cat” and “tree”.字符串c的tt比较靠前,不能与ab串的t顺序对应。
这里写图片描述

这里我们用深搜的方法。不过仅DFS,运行显示执行1000ms并TLE,剪枝后,显示31ms并AC。
我们定义了一个vis[][]的二维数组,如果出现重复搜索的方案直接断掉递归。

#include<stdio.h>#include<string.h>#include<cmath>using namespace std;char a[205],b[205],c[410];bool vis[205][205];int isOk=0;void dfs(int x,int y,int z){    if(vis[x][y]) return ;//被访问过    if(c[z]=='\0'){        isOk=1;        return ;    }    if(a[x]==c[z])        dfs(x+1,y,z+1);    if(b[y]==c[z])        dfs(x,y+1,z+1);    vis[x][y]=1;//已访问,标记!}int main(){    int T,cse;    scanf("%d",&T);    for(int cse=1;cse<=T;cse++)    {        for(int i=0;i<205;i++)//初始化            for(int j=0;j<205;j++)                vis[i][j]=0;        scanf("%s%s%s",a,b,c);        dfs(0,0,0);        printf("Data set %d: %s\n",cse,isOk?"yes":"no");        isOk=0;//初始化    }    return 0;}