輸入若干單詞(每行一個,空行結束),然後若干查詢單詞。對每個查詢,輸出字典中以該單詞為前綴的單詞數量。單詞長度 ≤ 10,小寫字母。內存限制較大。
#includeusing namespace std; struct Trie { Trie* next[26]; int cnt; Trie() : cnt(0) { memset(next, 0, sizeof(next)); } }; Trie* root = new Trie(); void insert(const char* s) { Trie* p = root; for (; *s; ++s) { int id = *s - 'a'; if (!p->next[id]) p->next[id] = new Trie(); p = p->next[id]; ++p->cnt; } } int query(const char* s) { Trie* p = root; for (; *s; ++s) { int id = *s - 'a'; if (!p->next[id]) return 0; p = p->next[id]; } return p->cnt; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; while (getline(cin, s) && !s.empty()) insert(s.c_str()); while (getline(cin, s)) cout << query(s.c_str()) << '\n'; return 0; }
Trie 樹經典應用:前綴計數。節點存 `cnt` 即以該前綴為前綴的單詞數,插入時累加,查詢 O(L) 直接返回。代碼極簡,內存足夠時直接 `new` 節點最省事。