P1019 单词接龙(C++_DFS_回溯)

题目描述

单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。

输入格式

输入的第一行为一个单独的整数n (n≤20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.

输出格式

只需输出以此字母开头的最长的“龙”的长度

输入输出样例

输入 #1

5
at
touch
cheat
choose
tact
a

输出 #1

23

说明/提示

(连成的“龙”为atoucheatactactouchoose)

NOIp2000提高组第三题

反思

这个题真的反思良多,递归一直是我的弱项,而以递归为基础的DFS更是心病,解这道题所遇到的问题或反思且听我细细道来:

1. 数据结构

别总就想着用那些现成的容器,就拿vector来说,确实很方便可是数组或字符串一样可以啊,用了vector以后,各个函数的接口处的数据类型转换会磨完你的信心;

2.函数接口

在写算法的时候不要纠结于各个细节函数的实现,如果在写算法的时候需要某项功能,请先假设此功能函数已实现, 并想清楚在此算法中该函数到底需要什么参数和返回值,函数的接口很重要,先完成算法,再写功能函数,先整体后局部,不然具体功能函数的实现会打断算法的思路!

3.深度优先搜索中的回溯

回溯之后会不会又走进这个分支?这不就是死循环了么?显然没有!那么回溯之后又没有标记,电脑是怎么知道该换分支了呢?答案就在dfs函数中的for循环上, for循环的i值一直在变,这本身就是一种标记了!(刚开始写回溯算法的时候没写循环可真是愁死个人~)

源码

#include<bits/stdc++.h>
using namespace std;
class nodee
{
public:
	nodee():num(0){}//构造函数,顺便初始化num
	string vel;
	int num;//每个单词最多使用两次
};
nodee a[21];
int n, maxx = 1;
int findd(string a, string b)//输出最少重复
{
	for (int i = 1; i <= min(a.size(), b.size()); i++)//重复i个字母
	{
		int flag = 1;
		for (int j = 0; j < i; j++)//逐个比较
			if (a[a.size() + j - i] != b[j])
			{
				flag = 0;
				break;
			}
		if (flag)
			return i;
	}
	return 0;
}
int dfs(string s, int len)//深度优先搜索
{
	int same = 0;
	for (int i = 0; i < n; i++)
	{
		if (a[i].num == 2)
			continue;
		same = findd(s, a[i].vel);//重复长度
		if (same)//若不重复则跳过a[i]
		{
			a[i].num++;
			len += a[i].vel.size() - same;
			dfs(a[i].vel, len);//递归
			len -= a[i].vel.size() - same;//回溯
			a[i].num--;
		}
	}
	maxx = max(maxx, len);//更新最大长度
	return maxx;
}
int main()
{
	cin >> n;
	for (int i = 0; i <= n; i++)
		cin >> a[i].vel;//a[n].vel为开头字母
	dfs(a[n].vel, 1);
	cout << maxx;
	return 0;
}
### 华为OD模式下单词接龙C++实现 以下是基于给定规则的C++实现方案,该程序能够处理输入的一单词并按规则形成最长的单词串。 #### 1. 数据结构设计 为了高效查找符合条件的下一个单词,可以使用哈希表来存储每个首字母对应的候选单词列表。对于每一个可能的首字母,维护一个优先队列(最大堆),以便快速获取满足条件的最大长度单词或字典序最小的单词[^3]。 ```cpp #include <iostream> #include <vector> #include <unordered_map> #include <queue> #include <string> using namespace std; // 定义比较函数用于优先队列 struct Compare { bool operator()(const string& a, const string& b) { if (a.size() != b.size()) return a.size() < b.size(); // 按长度降序排列 return a > b; // 如果长度相等则按字典序升序排列 } }; ``` #### 2. 主逻辑实现 通过递归回溯的方式尝试构建最长的单词链。每次从当前单词的最后一个字符出发,在哈希表中寻找合适的后续单词,并标记已使用的单词以防重复使用。 ```cpp bool dfs(const unordered_map<char, priority_queue<string, vector<string>, Compare>>& wordMap, char lastChar, unordered_set<string>& usedWords, string& result, int& maxLength) { // 更新结果字符串和最大长度 if (result.length() > maxLength) { maxLength = result.length(); } // 查找以lastChar开头的所有可用单词 if (wordMap.find(lastChar) == wordMap.end()) return false; auto tempQueue = wordMap.at(lastChar); while (!tempQueue.empty()) { string nextWord = tempQueue.top(); tempQueue.pop(); if (usedWords.count(nextWord)) continue; // 跳过已使用的单词 usedWords.insert(nextWord); // 标记此单词已被使用 result += nextWord; // 将其加入结果字符串 if (dfs(wordMap, nextWord.back(), usedWords, result, maxLength)) { return true; // 成功找到更长路径 } // 回溯操作 result.erase(result.length() - nextWord.length()); usedWords.erase(nextWord); } return false; } void findLongestChain(vector<string> words, string startWord) { unordered_map<char, priority_queue<string, vector<string>, Compare>> wordMap; for (auto &word : words) { if (!word.empty()) { wordMap[word[0]].push(word); // 构建映射关系 } } unordered_set<string> usedWords; string result = startWord; int maxLength = 0; usedWords.insert(startWord); // 插入初始单词至集合 dfs(wordMap, startWord.back(), usedWords, result, maxLength); cout << "The longest chain is: " << result.substr(0, maxLength) << endl; } ``` #### 3. 测试案例 提供一些测试数据验证算法的有效性和正确性: ```cpp int main() { vector<string> testWords = {"apple", "eggs", "snack", "karat", "steak", "eclair"}; string startWord = "apple"; findLongestChain(testWords, startWord); return 0; } ``` 以上代码实现了根据规则构造最长单词链条的功能,并考虑到了各种边界情况如无解的情况或者存在多条同样长度的最优解等问题[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chaoql

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值