字典树==
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #define mem0(a) memset(a, 0, sizeof(a)) 6 using namespace std; 7 char str[200000]; 8 struct Trie { 9 int ch[200000][30]; 10 int val[200000]; 11 int last[200000]; 12 char cha[200000]; 13 int sz; 14 Trie() { 15 sz = 1; 16 mem0(ch[0]); 17 } 18 int idx(char c) { 19 return c - 'a'; 20 } 21 void insert(char s[]) { 22 int u = 0, n = strlen(s); 23 for(int i = 0; i < n; i++) { 24 int c = idx(s[i]); 25 if(!ch[u][c]) { 26 mem0(ch[sz]); 27 val[sz] = 0; 28 last[sz] = u; 29 cha[sz] = c; 30 ch[u][c] = sz++; 31 } 32 u = ch[u][c]; 33 } 34 val[u]++; 35 } 36 void outp(int nn) { 37 if(nn == 0) return; 38 outp(last[nn]); 39 putchar(cha[nn] + 'a'); 40 } 41 int solve() { 42 int ans = 0, mark = 0; 43 for(int i = 0; i < sz; i++) { 44 if(val[i] > ans) { 45 ans = val[i]; 46 mark = i; 47 } 48 } 49 outp(mark); 50 cout<< endl<< ans<< endl; 51 } 52 }; 53 Trie S; 54 int main() 55 { 56 //输入很多用空格隔开的单词(只包含小写字母) 57 //输出出现次数最多的单词以及出现的次数 58 while(~scanf("%s", str)) S.insert(str); 59 S.solve(); 60 return 0; 61 }