首页 > ACM题库 > HDU-杭电 > HDU 1501 Zipper-动态规划-[解题报告] C++
2013
12-11

HDU 1501 Zipper-动态规划-[解题报告] C++

Zipper

问题描述 :

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".

输入:

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.

输出:

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.

样例输入:

3
cat tree tcraete
cat tree catrtee
cat tree cttaree

样例输出:

Data set 1: yes
Data set 2: yes
Data set 3: no

DP解法:
最优子结构分析:如上例,如果A、B可以组成C,那么,C最后一个字母e,必定是 A 或 C 的最后一个字母组成。
C去除除最后一位,就变成是否可以求出 A-1和B 或者 A与B-1 与 是否可以构成 C-1。。。
状态转移方程:

用f[i][j] 表示 表示A前 i 为 和B 前j 位是否可以组成 C的前i+j位        

        dp[i][j]= (dp[i-1][j]&&(a[i]==c[i+j]))||(dp[i][j-1]&&(b[j]==c[i+j]))

代码:

#include<stdio.h>
#include<string.h>

char a[201],b[201],c[402];
int la,lb,lc;
int dp[201][201];

int main()
{
	int ncase;
	scanf("%d",&ncase);
	for(int n=1; n<=ncase; n++) {
		
		a[0]='p';
		b[0]='p';
		c[0]='p';
		
		scanf("%s%s%s",a+1,b+1,c+1);
		
		la=strlen(a);
		lb=strlen(b);
		lc=strlen(c);
		
		la-=1;
		lb-=1;
		
		//处理边界
		for (int i=1; i<=la; i++)
			if (a[i]==c[i]) dp[i][0]=1; 
		
		for (int i=1; i<=lb; i++)
			if (b[i]==c[i]) dp[0][i]=1;
		//DP
		for (int i=1; i<=la; i++)
			for (int j=1; j<=lb; j++)
				dp[i][j]= (dp[i-1][j]&&(a[i]==c[i+j]))||(dp[i][j-1]&&(b[j]==c[i+j]));
		
		printf("Data set %d: ",n);
		if (dp[la][lb]==1) printf("yes\n");
		else printf("no\n");
		
	}
}
a

解题报告转自:http://www.cnblogs.com/andyzhang2068/archive/2011/07/08/2101514.html


  1. 算法是程序的灵魂,算法分简单和复杂,如果不搞大数据类,程序员了解一下简单点的算法也是可以的,但是会算法的一定要会编程才行,程序员不一定要会算法,利于自己项目需要的可以简单了解。