标签:
输入一系列字符串构成trie树 T ,空行,再输入字符串,查询 T 中以这些字符串为前缀的字符串数量。通过修改插入时,对 count 的操作,可以实现很多变形功能。杭电1251,1671
#include<iostream> #include<vector> #include<queue> #include<string> using namespace std; #define TRIEMAX 26 struct trieNode{ int count; trieNode* childs[TRIEMAX]; trieNode(){ count = 0; for (int i = 0; i < TRIEMAX; ++i) childs[i] = NULL; } }; void insertTrie(trieNode* root, string s) { int k; trieNode *cur = root; for (int i = 0; i < s.size(); ++i){ k = s[i] - ‘a‘; if (cur->childs[k] != NULL){ cur = cur->childs[k]; ++(cur->count); } else{ cur->childs[k] = new trieNode; ++(cur->childs[k]->count); cur = cur->childs[k]; } } } int searchTrie(trieNode* root, string s){ int k; trieNode *cur = root; for (int i = 0; i < s.size(); ++i){ k = s[i] - ‘a‘; if (cur->childs[k] == NULL) return 0; cur = cur->childs[k]; } return cur->count; } void showTrie(trieNode* root){ trieNode* p = NULL; queue<trieNode*> q; q.push(root); while (!q.empty()){ p = q.front(); q.pop(); if (p){ cout << p->count << ‘ ‘; for (int i = 0; i < TRIEMAX; ++i) q.push(p->childs[i]); } } cout << endl; } /* 测试数据 banana band bee absolute acm ba b band abc */ int main() { trieNode* root = new trieNode; string s; while (getline(cin,s)){ if (!s.empty()){ insertTrie(root, s); } else{ showTrie(root); while (getline(cin,s)){ if (s.empty()) return 0; cout << searchTrie(root, s) << endl; } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/jokoz/p/4768376.html