标签:
题目链接:https://www.facebook.com/hackercup/problems.php?pid=313229895540583&round=344496159068801
题目大意:自己看去(其实我也说不清)
裸的Trie树,直接看是否存在必须插入的节点。
代码写的太挫了。。将就着看吧。。
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #include <vector> 5 #include <cstdlib> 6 using namespace std; 7 #define CHARSET 26 8 9 const int MAX_NODE = 10000000; 10 11 struct trieNode{ 12 int ch[CHARSET]; 13 }; 14 trieNode trie[MAX_NODE]; 15 int ptr; 16 int ans; 17 18 int T,N; 19 char str[MAX_NODE]; 20 21 22 void init(){ 23 ptr = ans = 0; 24 for(int i=0;i<CHARSET;i++){ 25 trie[0].ch[i] = -1; 26 } 27 } 28 29 int newNode(){ 30 ptr++; 31 for(int i=0;i<CHARSET;i++){ 32 trie[ptr].ch[i] = -1; 33 } 34 return ptr; 35 } 36 37 void insert(const char* str){ 38 bool hasAdded = false; 39 int len = strlen(str); 40 int rt = 0; 41 for(int i=0;i<len;i++){ 42 int id = str[i] - ‘a‘; 43 if( trie[rt].ch[id]==-1 ){ 44 trie[rt].ch[id] = newNode(); 45 if( !hasAdded ){ 46 ans = ans + i + 1; 47 hasAdded = true; 48 // printf("+%d\n",i+1); 49 } 50 } 51 rt = trie[rt].ch[id]; 52 } 53 if(!hasAdded){ 54 ans = ans + len; 55 // printf("+%d\n",len); 56 } 57 } 58 59 int main(){ 60 // freopen("input.txt","r",stdin); 61 // freopen("output.txt","w",stdout); 62 scanf("%d",&T); 63 for(int cases = 1;cases <= T ; cases++){ 64 scanf("%d",&N); 65 init(); 66 for(int i=0;i<N;i++){ 67 scanf("%s",str); 68 insert(str); 69 } 70 printf("Case #%d: %d\n",cases,ans); 71 } 72 return 0; 73 }
[HackerCup Round1 2] Autocomplete (Trie)
标签:
原文地址:http://www.cnblogs.com/llkpersonal/p/4235981.html