poj_2192Zipper

链接:http://poj.org/problem?id=2192


和数塔一样,中间存在重复子问题。用一个数组记录是否被访问过,也就是记忆化搜索了。

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
bool dp[205][205];
bool flag;
string sa, sb, sc;

void DFS(int i, int j, int k)
{
	if(k == sc.size())
	{
		flag = true;
		return;
	}
	if(flag) return;
	if(dp[i][j]) return;
	dp[i][j] = true;
	if(i < sa.size() && sa[i] == sc[k])
	{
		DFS(i + 1, j , k + 1);
	}
	if(j < sb.size() && sb[j] == sc[k])
	{
		DFS(i, j + 1, k + 1);
	}
}

int main()
{
	freopen("in.txt","r",stdin);
	int n;
	cin >> n;
	for(int i = 1; i <= n; i++)
	{
		cin >> sa >> sb >> sc;
		memset(dp, false, sizeof(dp));	
		flag = false;
		DFS(0, 0, 0);
		if(flag)
		{
			cout << "Data set " << i << ": yes" << endl;
		}
		else
		{
			cout << "Data set " << i << ": no" << endl;
		}
		sa.clear();
		sb.clear();
		sc.clear();
	}
	return 0;
}




原文地址:https://www.cnblogs.com/lgh1992314/p/5835164.html