cmu15445
project 0 Trie 通关指北
前置知识
- 简单版Trie树,leetcode题源实现Trie树
- 学习cpp智能指针, 推荐modern effective cpp看相关chapter
- 仔细阅读实验手册
task1个人心得
该图到下图是如何变换来的?
我简单画一下walk完之后的样子,怎么把它重新连起来?
答案是使用栈,在walk的使用将节点在栈里面存一边,最后反向迭代ad,建立trie树。
get的方法比较简单不用多说,remove其实和put的操作是一样的,也是要clone后重新连。
put需要注意的点
- adcf这种情况,walk进栈的时候,你新创建了一个节点后后面该如何处理(walk到a的时候发现d节点是不存在的,所以你创建 了一个新节点d, d之后的节点该如何处理)。
- 另外还有复制结点的使用应该使用多态clone函数:因为你不知道他是不是带值节点,clone之后这个节点不是const了,你也可以修改。
- 叶子节点是否是已经存在的但他不是一个带值节点
remove需要注意
1.当你remove的节点是带值节点,但他有孩子,如何删除(答案是使用其children构造函数创建一个节点,而不是使用clone)
virtual auto Clone() const -> std::unique_ptr<TrieNode> { return std::make_unique<TrieNode>(children_); }
最后贴一下反向建Trie的代码,也就是put的后半部分
std::unique_ptr<TrieNode> leaf_node;
// do not exist before, newly created
if (cur == nullptr) {
leaf_node = std::make_unique<TrieNodeWithValue<T>>(val);
} else { // exist before
leaf_node = std::make_unique<TrieNodeWithValue<T>>(cur->children_, val);
}
auto pre = std::move(leaf_node);
std::unique_ptr<TrieNode> curr = nullptr;
for (auto it = key.rbegin(); it != key.rend(); ++it) {
std::cout << *it << std::endl;
curr = std::move(st.top());
st.pop();
curr->children_[*it] = std::shared_ptr<const TrieNode>(std::move(pre));
pre = std::move(curr);
}
//
return Trie{std::shared_ptr<const TrieNode>(std::move(pre))};
task2
- put,remove的方法现在不返回trie,所以实际上是最后对root进行换根的操作,put,get,和remove的方法和task1是差不多的(怎么换? 在函数里面自己创建个新根,最后使用移动赋值给root就行了)
- 熟悉下scope_lock,unique_lock, 和lock_guard;
- get获取的时候要加根锁,并且马上释放,为什么那,多线程的情况下,想想get get put的情况,如果put先于第二个get进行会怎么样,如果get不加根锁,会怎么样?put和remove要加写锁, 另外在获取根和更新根的时候要加根锁
task3
这个好像有点问题,我debug出来的答案通不过测评,网上好像有如何改正的, 我没有改,最后评测94分
我主要讲一下vscode如何debug
我的环境wsl2 Ubuntu 22.04 调试器lldb,修改launch.json这个文件,将文件路径改为你调试的文件的路径几个,直接命令行使用pwd查看可执行文件路径然后赋值进黄色方框即可,最后按f5即可调试(没办法我不太会使用命令调试)。
task4
修改/string_expression.h中的compute即可,根据枚举的类型使用tolower和touppper。
project0 over