HDU1501 Zipper DFS+记忆化搜索

    该题理解为将每一个字母与两个模式串进行匹配,如果不符合则回溯进行匹配。

一个例子:   aaabb  aaaaaacd aaaaaacaaabbd

到组合串第四个字母时,'a' 不能够与A串匹配,于是以状态为A:aaa__, B: a_______,组合串匹配到第五个字母进行递归,......当匹配到组合串的第七个字母 'c'时,该字母与A串以及B串的第四个字母均不能匹配,这时必定将回溯到组合串第三个'a'的匹配过程中,并将第三个 'a' 分配给B串,而这时,A串又会和组合串中的第四个'a' 匹配,接下来,又将以A:aaa__, B: a_______,组合串匹配到第五个字母进行递归过程。注意,这里就产生了跟前面相同的情况了,所以记忆化搜索便是剪枝的最佳方式。

    代码如下:

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

char w1[205], w2[205], s[410];

int flag1, flag2, len1, len2, lens, hash[205][205];

void DFS( int x, int cnt1, int cnt2 )
{
	if( x== lens )
	{
	    flag2= 1;
		return;
	}
	if( hash[cnt1][cnt2] )
	{
	    return;
	}
	hash[cnt1][cnt2]= 1;
	if( s[x]== w1[cnt1] )
	{
		DFS( x+ 1, cnt1+ 1, cnt2 );
	}
	if( s[x]== w2[cnt2] )
	{
		DFS( x+ 1, cnt1, cnt2+ 1 );
	}
}

int main(  )
{
	int T;
	scanf( "%d", &T );
	for( int t= 1; t<= T; ++t )
	{
	    memset( hash, 0, sizeof( hash ) );
		flag1= flag2= 0;
		scanf( "%s%s%s", w1, w2, s );
		len1= strlen( w1 );
		len2= strlen( w2 );
		lens= strlen( s );
		DFS( 0, 0, 0 );
		printf( flag2== 1? "Data set %d: yes\n": "Data set %d: no\n", t );
	}
	return 0;
}

/*
3
cat tree tcraete
cat tree catrtee
cat tree cttaree

7
cat tree cttaree
Cat tree tCraete
vvv vvaa vvvaavv
abd hcda hcadbda
cat tree catrtee
bii iiii iiiibii 
ddf fdd  fdddfd
*/
原文地址:https://www.cnblogs.com/Lyush/p/2108603.html