hdoj 1501 Zipper 【DFS + 剪枝】

Zipper

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7761    Accepted Submission(s): 2742


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
 

简单DFS,主要剪枝。。。TLE到死,醉了

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char a[200+10], b[200+10], c[400+10];
int va[200+10], vb[200+10];
int la, lb, lc;
int exist;
void dfs(int pa, int pb, int pc)
{
	if(exist) return ; 
	if(pc >= lc)
	{
		exist = 1;
		return ;
	}
	if(c[pc] == a[pa] && !va[pa] && pa < la)//pa位置没搜索 且当前搜素长度小于 a字符串长度 
	{
		va[pa] = 1;
		dfs(pa+1, pb, pc+1);
		va[pa] = 0;
	} 
	if(c[pc] == b[pb] && !vb[pb] && pb < lb)//同上 
	{
		vb[pb] = 1;
		dfs(pa, pb+1, pc+1);
		vb[pb] = 0;
	} 
} 
int main()
{
	int t;
	int j = 1;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%s%s%s", a, b, c);
		la = strlen(a);
		lb = strlen(b);
		lc = strlen(c);
		if(la + lb != lc || (a[la-1] != c[lc-1] && b[lb-1] != c[lc-1]))//剪枝。。。
		{
			printf("Data set %d: no\n", j++);
			continue;
		}
		memset(va, 0, sizeof(va));
		memset(vb, 0, sizeof(vb));
		exist = 0;
		dfs(0, 0 ,0);
		if(exist)
		printf("Data set %d: yes\n", j++);
		else
		printf("Data set %d: no\n", j++);
	}
	return 0;
}


你可能感兴趣的:(hdoj 1501 Zipper 【DFS + 剪枝】)