标签:
分析:一道简单的字典树的题目,一开始用G++提交总是MLE ,尝试再写个释放内存的函数,竟然比原先的内存占用更大了。很无语。。。。后来改用C++提交竟然减少了一半内存,而且AC了。!!
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 50021 typedef struct trie { trie *next[26]; int v; //字符相同的个数 }trie; trie *root; void creat_trie(char str[]) { int len = strlen(str); trie *p = root; for(int i=0; i<len; ++i) { int id = str[i]-'a'; if(p->next[id] == NULL) { p->next[id] = (trie *)malloc(sizeof(trie)); p->next[id]->v = 1; p = p->next[id]; for(int j=0; j<26; ++j) p->next[j] = NULL; } else { p->next[id]->v++; p = p->next[id]; } } } int find_trie(char str[]) { int len = strlen(str); trie *pp = root; for (int i=0;i<len;i++) { int id = str[i] - 'a'; pp = pp->next[id]; if(pp == NULL) return 0; //没有符合 } return pp->v; // 此字符串为字符集中某串的前缀 } int main() { int N,n,i,j,s,t,m,flag=0; int a,b,c,d; int sum; char str[15]; root = (trie *)malloc(sizeof(trie)); for (i=0;i<26;i++) { root->next[i] = NULL; } while (gets(str) && str[0] != 0) { creat_trie(str); } while (scanf("%s",str) != EOF) { int k=find_trie(str); printf("%d\n",k); } //deal(root); return 0; }
#include <cstdio> #include <cstring> #include <iostream> using namespace std; struct trie { trie *next[26]; int v; //字符相同的个数 trie() { memset(next,NULL,sizeof(next)); v=0; } }; trie *root=new trie(),*p; void creat_trie(char *str) { int i,id; for(p = root,i=0;str[i]; ++i) { id = str[i]-'a'; if(p->next[id] == NULL) { p->next[id] = new trie(); } p = p->next[id]; p->v++; } } int find_trie(char *str) { int i,id; for (p=root,i=0;str[i];i++) { id = str[i] - 'a'; p = p->next[id]; if(p == NULL) return 0; } return p->v; // 此字符串为字符集中某串的前缀 } int main() { int N,n,i,j,s,t,m,flag=0; int a,b,c,d; int sum; char str[15]; while (gets(str),*str) { creat_trie(str); } while (gets(str)) { printf("%d\n",find_trie(str)); } return 0; }
banana band bee absolute acm ba b band abc
2 3 1 0
标签:
原文地址:http://blog.csdn.net/xinwen1995/article/details/46364581