动态规划14 Zipper

Zipper

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 30   Accepted Submission(s) : 13

Font: Times New Roman | Verdana | Georgia

Font Size:  

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

AC代码

#include<iostream>
#include<string>
using namespace std;

bool dp[403][403];

int main()
{
	string str1;
	string str2;
	string str3;
	int t;
	cin >> t;
	for(int i=1;i<=t;++i)
	{
		cin >> str1 >> str2 >> str3;
		printf("Data set %d: ", i);
		if (str1.size() + str2.size() != str3.size())
		{
			cout << "no" << endl;
			continue;
		}//很小的剪枝
		dp[0][0] = true;
		for (int j = 1; j <=str1.size(); ++j)
		{
			if (str1.substr(0, j) == str3.substr(0, j))
				dp[j][0] = true;
			else
				dp[j][0] = false;
		}//初始条件设置
		for (int j = 1; j <= str2.size(); ++j)
		{
			if (str2.substr(0, j) == str3.substr(0, j))
				dp[0][j] = true;
			else
				dp[0][j] = false;
		}
		for (int j = 1; j <= str1.size(); ++j)
		{
			for (int k = 1; k <= str2.size(); ++k)
			{
				if ((dp[j - 1][k] && str1[j - 1] == str3[j + k - 1]) || (dp[j][k - 1] && str2[k - 1] == str3[j + k - 1]))
					dp[j][k] = true;//str1的前j个字母和str2的前k个字母是否能够组成str3的前j+k个字母,考虑前一种状态
				else
					dp[j][k] = false;
			}
		}
		if (dp[str1.size()][str2.size()])
			cout << "yes" << endl;
		else
			cout << "no" << endl;

	}
	system("pause");
	return 0;
}



猜你喜欢

转载自blog.csdn.net/qq_36921652/article/details/79204092
今日推荐