HDU 1501 Zipper

Zipper

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

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 

这题完全是看别人的DP思想写出来的,对于刚接触DP的我,还是不太会写,代码是搞懂了自己敲的。

大体思想是,sum的最后一个元素总是和str1的最后一个元素,或者str2的最后一个元素相等,这就可以看成dp【i-1】【j】或者dp【i】【j-1】的问题

这就是把问题转换到了小问题上,有了子结构。

上AC代码

#include <stdio.h>
#include <string.h>
int dp[205][205];
int main()
{
	char str1[205],str2[205],sum[405];
	int n,i,j,k,len1,len2; 
	scanf("%d",&n);
	for(i=1;i<=n;i++)
	{
		scanf("%s %s %s",str1,str2,sum);
		len1=strlen(str1);
		len2=strlen(str2);
		memset(dp,0,sizeof(dp));
		for(j=1;j<=len1;j++)
			dp[j][0]=(str1[j-1]==sum[j-1]);
		for(k=1;k<=len2;k++)
			dp[0][k]=(str2[k-1]==sum[k-1]);
		for(j=1;j<=len1;j++)
		{
			for(k=1;k<=len2;k++)
			{
				dp[j][k]=(str1[j-1]==sum[j+k-1] && dp[j-1][k] || str2[k-1]==sum[j+k-1] && dp[j][k-1]);
			}
		}	
		if(dp[len1][len2])
			printf("Data set %d: yes\n",i);
		else
			printf("Data set %d: no\n",i);
	}
	
	return 0;
}



你可能感兴趣的:(HDU 1501 Zipper)