字典树(Trie Tree)是一种非常简单而又常用的数据结构,他就是将字符串插入到一棵树中,从而形成字典。 举个简单的例子,我们有26个小写字母,那么我们在每个树的节点设置26个指针,分别代表指向'a' ~ 'z',这样除了根节点之外的每个结点可以看作是代表一个字母,其所处深度代表这个字符所处字符串的位置。 其操作非常简单,一般静态分配即申请一个较大的空间作为备用,根结点指向第一个空间。当执行插入操作的时候,从根结点依次往下遍历,如果发现对应字母位置的深度已存在该字母的话,我们将指针移到那个位置。倘若没有对应字母的话,我们将分配一个空间给对应字母而产生一个新的结点。搜索同理,当要查找的字符串未遍历完毕而发现当前结点找不到下一个对应字母位置的结点的话,证明树中没有这个串,跳出。当然动态分配也同理。 做个简单的题作为例子:
Flying to the MarsTime Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
Input
Input file contains multiple test cases.
In a test case,the first line contains a single positive number N indicating the number of soldiers.(0<=N<=3000)
Next N lines :There is only one nonnegative integer on each line , indicating the level number for each soldier.( less than 30 digits);
Output
For each case, output the minimum number of broomsticks on a single line.
Sample Input
4 10 20 30 04 5 2 3 4 3 4
Sample Output
1 2 |
/************************************************************************* > File Name: Flying_to_the_Mars.cpp > Author: ZhangHaoRan > Mail: chilumanxi@gmail.com > Created Time: 2016年06月04日 星期六 20时21分09秒 ************************************************************************/ #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<vector> #include<set> #include<map> #include<queue> #include<list> #include<algorithm> using namespace std; int ans = 0; char num[35]; int N; struct node{ node *nexti[10]; int v; }tt[5000001]; node *root; char tempch[30]; int tot = 1; void add(char *str){ int i = 0; node *temp = root; while(str[i]){ if(temp -> nexti[str[i] - '0'] == 0){ temp -> nexti[str[i] - '0'] = &tt[tot ++]; temp = temp -> nexti[str[i] - '0']; temp -> v = 0; for(int j = 0; j < 10; j ++){ temp -> nexti[j] = 0; } } else{ temp = temp -> nexti[str[i] - '0']; } i ++; } temp -> v ++; if(temp -> v > ans){ ans = temp -> v; } } int main(void){ root = &tt[0]; while(cin >> N){ if(!N){ cout << 0 << endl; continue; } for(int i = 0; i < 10; i ++){ root -> nexti[i] = 0; } ans = 1; tot = 1; for(int i = 0; i < N; i ++){ scanf("%s", tempch); int len = strlen(tempch); int j = 0; for(; j < len; j ++){ if(tempch[j] == '0'){ continue; } else break; } if(j != len){ for(int i = 0; j < len; i ++, j ++){ num[i] = tempch[j]; if(j == len - 1) num[i + 1] = 0; } } else{ num[0] = '0'; num[1] = 0; } add(num); } cout << ans << endl; } return 0; }在每次插入的时候寻找此前这个串被插入几次。
查看原文:http://chilumanxi.org/2016/06/04/%e6%b5%85%e8%b0%88%e5%ad%97%e5%85%b8%e6%a0%91/