#include <stdio.h> #include <stdlib.h> #include <string.h> int const N= 1000000; struct Trie{ int id; // 标记每一个单词 int cnt; // 标记单词前缀的数量 int next[26]; // 26 个孩子结点 void init(){ id= 0; cnt= 0; for( int i= 0; i< 26; ++i ) next= 0; } }; Trie tree[N]; int num= 0, root= 0, cid= 0; void insert( char* s ){ int rt= root; while( *s ){ int t= *s- 'a'; if( tree[rt].next[t]== 0 ){ tree[++num].init(); tree[rt].next[t]= num; } rt= tree[rt].next[t]; tree[rt].cnt++; s++; } tree[rt].id= ++cid; } int find( char* s ){ int rt= root; while( *s ){ int t= *s- 'a'; rt= tree[rt].next[t]; if( rt== 0 ) return 0; s++; } return tree[rt].cnt; } int main(){ char str[100]; while( gets(str)!= NULL ){ if( strlen(str)== 0 ) break; insert( str ); } while( gets(str)!= NULL ) printf("%d\n", find(str) ); return 0; }
Another implement: http://www.cnblogs.com/Xredman/archive/2009/04/10/1433167.html