现在的位置: 首页 > 综合 > 正文

POJ 2192 Zipper 解题报告

2013年01月26日 ⁄ 综合 ⁄ 共 2289字 ⁄ 字号 评论关闭

Language:
Zipper
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 12609   Accepted: 4399

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

这题很水,题意就是3个字符串,如果第三个能由前两个字符串按顺序构成就yes,否则就no

理论上来说这题是一个DP的

但是这里我用DFS的方法也A了...

超时N次+剪枝才过...搜索的方法也是一个坑点

第一个剪枝:判断两个字符串的末尾是否有一个和标准字符串是否相等

第二个剪枝:两个字符串的位数和要等于第三个字符串的位数

坑点:

我先搜索第二个字符串再搜索第一个就WA...

反过来先搜索第一个再搜索第二个就A了...

#include<algorithm>
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cstdio>
const int MAX = 410;
using namespace std;
string a,b,c;
int len1,len2,len3;
int find(int a1,int b1,int c1) // a,b,c的下标
{
	if(len1==a1&&len2==b1)
		return 1;
	if(c[c1] == a[a1] && a1<len1)
			if(find(a1+1,b1,c1+1))
				return 1;
	if(c[c1] == b[b1] && b1<len2)
			if(find(a1,b1+1,c1+1))
				return 1;
	
	return 0;
}
int main()
{
	int n;
	scanf("%d",&n);
	int i;
	for(i=1;i<=n;i++)
	{
		cin>>a>>b>>c;
		len1 = a.size();
		len2 = b.size();
		len3 = c.size();
		if(c[len3-1] != b[len2-1] && c[len3-1] != a[len1-1] || (len1 + len2 !=len3))
			printf("Data set %d: no\n",i);
		else
		{
			if(find(0,0,0))
				printf("Data set %d: yes\n",i);
			else
				printf("Data set %d: no\n",i);
		}
	}	
	return 0;
}

 

抱歉!评论已关闭.