字典树
字典树 是一种树形结构,是一种哈希树的变种。应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。
优点:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。
主要用于 用于字符串的快速搜索、字符串的(字典序)排序, 求一组字符串的公共前缀
typedef struct tree{ int data; //记录所需数据
struct tree *next[27];//记录有多少分支
} tree;
题目链接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1115
字典树模板~~
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string> using namespace std; typedef struct tree{ int len; //记录此点有几个单词共用 struct tree *next[27]; } tree; tree *root; int sum, sum1; void init(){ root = new tree; root->len=0; for(int i=0; i<27; i++){
root->next[i] = NULL; }
} void create(string s){ //建立字典树int j=0, a=s.size(); tree *temp = root; while(j<a){ if(temp->next[s[j]-'a'] == NULL){ tree *temp1; temp1 = new tree; temp1->len=0; for(int i=0; i<27; i++){ temp1->next[i] = NULL; }
temp->next[s[j]-'a'] = temp1; } temp = temp->next[s[j]-'a']; temp->len++; j++; } } void dfs(tree *p) {//递归确定最短字符总长 if(p == NULL) r
return ; sum1 += p->len; if(p->len==1)
return; for(int i=0; i<27; i++){
dfs(p->next[i]); }
} int main() { //freopen("input.txt", "r", stdin); int t; scanf("%d", &t); while(t--) { int n, i; string s; init(); cin>>n; for(i=0; i<n; i++){ cin>>s; create(s); } for(sum=0, i=0; i<27; i++){ sum1=0; dfs(root->next[i]); sum += sum1; } printf("%d\n", sum); } return 0; }

浙公网安备 33010602011771号