• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

(step4.3.5)hdu 1501(Zipper——DFS)

题目大意:是给定3个字符串,问前两个是否能够组成第3个字符串。此题是个非常经典的dfs题.


解题思路:DFS


代码如下:有详细的注释

 

/*
 * 1501_2.cpp
 *
 *  Created on: 2013年8月17日
 *      Author: Administrator
 */

#include <iostream>
using namespace std;

char str1[201], str2[201], str3[401];
int len1, len2, len3;
bool flag;
bool hash[201][201];

/**
 * str1、str2、str3分别用来保存第1、2、3个字符串
 * len1、len2、len3分别是第1、2、3个字符串的长度
 * flag : 判断是否有解
 * hash[][] :判断是否已经访问过
 */
void dfs(int a, int b, int c) {
	if (flag) {
		return;
	}

	if (c == len3) {
		flag = true;
		return;
	}

	if (hash[a][b]) {
		return;
	}

	hash[a][b] = true;//这个千万不要漏了...表示这种组合已经试过
	if (str1[a] == str3[c]) {//如果str1第a个位置上的字符与str2第c个位置上的字符相等
		dfs(a + 1, b, c + 1);
	}

	if (str2[b] == str3[c]) {//如果str2第b个位置上的字符和str2第c个位置上的字符相等
		dfs(a, b + 1, c + 1);
	}
}

int main() {
	int t;

	scanf("%d", &t);
	int count = 1;
	int i;
	for( i = 1 ;i <= t ; ++i){
		flag = false;
		memset(hash, 0, sizeof(hash));
		scanf("%s%s%s", str1, str2, str3);

		len1 = strlen(str1);
		len2 = strlen(str2);
		len3 = strlen(str3);
		if (len1 + len2 != len3) {
			printf("Data set %d: no\n",count++);
			continue;
		}

		dfs(0, 0, 0);
		printf("Data set %d: %s\n", count++,flag?"yes":"no");

	}
}


 


 

posted @ 2013-08-17 21:41  Class Xman  阅读(169)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3