俺的trie漂亮,这可不是吹的
网上许多trie施肥很足,比如C++版参数是string而不是const string_view&, Python版不用dict
class TrieNode: def __str__(this): return str((id(this) - id(root)) // 64)
def __init__(this): this.kids = {}; this.hasWord = False def insert(this, str): if str == '': this.hasWord = True; return kid = this.kids.setdefault(str[0], TrieNode()) kid.insert(str[1:]) def find(this, str): if str == '': return this.hasWord kid = this.kids.get(str[0]) return kid.find(str[1:]) if kid is not None else False def print(this, n=0): space = ' ' * n def pr(*args, **kwargs): print(space, *args, **kwargs, sep='') pr(f"I'm node {this}. These are my kids: ", end='') for ch,kid in this.kids.items(): print(f"'{ch}':{kid}", end=' ') print() for _,kid in this.kids.items(): kid.print(n + 1) root = TrieNode() root.insert('abc'); root.insert('abd'); root.insert('ab') r = root; print(r.find('abc'), r.find('ab'), r.find('a')) r.print()
True True False I'm node 0. These are my kids: 'a':12 I'm node 12. These are my kids: 'b':14 I'm node 14. These are my kids: 'c':15 'd':16 I'm node 15. These are my kids: I'm node 16. These are my kids:
也许space改叫indent好。 indent, from in- ‘into’ + 拉丁语 dens, dent- ‘tooth’.
C++循环,bit流,平沙落雁不伦不类式:
#include <stdio.h> #include <stdint.h> #include <string.h> struct TrieNode; TrieNode* tnalloc(); class TrieNode { TrieNode* kids[2]; bool hasWord; int id; public: void insert (const void* buf, size_t n) { const uint8_t* bytes = (const uint8_t*)buf; TrieNode* p = this; while (n--) { for (uint8_t m = 0x80; m; m >>= 1) { const int i = bytes[n] & m ? 1 : 0; if (!p->kids[i]) p->kids[i] = tnalloc(); p = p->kids[i]; //printf("insert: %d\n", p->id); } } p->hasWord = true; //printf("%d has word\n", p->id); } bool find (const void* buf, size_t n) { const uint8_t* bytes = (const uint8_t*)buf; TrieNode* p = this; while (n--) { for (uint8_t m = 0x80; m; m >>= 1) { const int i = bytes[n] & m ? 1 : 0; if (!p->kids[i]) goto done; p = p->kids[i]; } } done: //printf("find: %d\n", p->id); return p->hasWord; } friend TrieNode* tnalloc(); }; TrieNode* tnalloc () { static TrieNode all[1000 * 1000]; static int n = 0; TrieNode* p = all + n++; p->kids[0] = p->kids[1] = 0; p->hasWord = false; p->id = n - 1; return p; } void insert(TrieNode* p, const char* s) { p->insert(s, strlen(s)); // 防"ab", 1 printf("%s in trie\n", s); } int main (int argc, char** argv) { if (argc != 2) return 0; TrieNode* r = tnalloc(); insert(r, "ab"); insert(r, "abc"); insert(r, "abd"); printf("%d\n", r->find(argv[1], strlen(argv[1]))); return 0; }
https://www.cs.usfca.edu/~galles/visualization/Algorithms.html
各种算法的动画,有trie的。再如八皇后的:
比如(人那个是会动的哦):

〔.tar.gz 3.7M〕可下载到本地运行。我搞了〔.7z 1.3M〕
树和树中的节点有时候不太好区分。指向数的指针是不是指向树根的指针?树根是不是个节点?
《读者》还是某杂志说外国有科学家研究结和环,结论是“结是环的一个系统”。研究Knot is not naughty, 是正儿八经的数学理论。
高斯想出了用数字串表示结的方法,但是同一个结可以有多种不同表示。
Perfect Hash函数不好找。有个老外把gpref的速度提高了一倍(也许不是所有情况),酸楚地抱怨没人感兴趣。

浙公网安备 33010602011771号