1. 程式人生 > >【hdu 1501】Zipper(最優子結構)

【hdu 1501】Zipper(最優子結構)

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<iostream>
#include<cstring>
using namespace std;
int main()
{
	char str1[220], str2[220], str3[550];
	int len1, len2, len3;
	int dp[220][220];
	int t;
	cin >> t;
	cin.get();
	int counts = 1;
	while (t--)
	{
		scanf("%s%s%s", str1 + 1, str2 + 1, str3 + 1);
		len1 = strlen(str1 + 1);
		len2 = strlen(str2 + 1);
		memset(dp, 0, sizeof(dp));
		for (int i=1;i<=len1;i++)
		if (str1[i] == str3[i])dp[i][0] = 1;
		for (int i = 1; i <= len2;i++)
		if (str2[i] == str3[i])dp[0][i] = 1;
		for (int i = 1; i <= len1;i++)
		for (int j = 1; j <= len2; j++)
			dp[i][j] = (dp[i - 1][j] && (str1[i] == str3[i + j])) || (dp[i][j - 1]&&(str2[j] == str3[i + j]));
		cout << "Data set " << counts++ << ": ";
		dp[len1][len2] == 1 ? cout << "yes" << endl: cout << "no" << endl;

	}
}