标签:des style blog io ar color os sp java
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 19054 Accepted Submission(s): 8418
字典树模板、= =
指针版、140MS
#include<iostream> #include<cstdio> #include<cstring> using namespace std; struct node { node *next[26]; int val; }; node *root; int getid(char ch) { return ch-‘a‘;} void Insert(char *s) { node *pre=root,*now; for(int i=0;s[i]!=‘\0‘;i++) { int id=getid(s[i]); now=pre->next[id]; if(!now) { now=new node; memset(now,0,sizeof(node)); pre->next[id]=now; } now->val++; pre=now; } } int Find(char *s) { node *pre=root,*now; for(int i=0;s[i]!=‘\0‘;i++) { int id=getid(s[i]); now=pre->next[id]; if(!now) return 0; pre=now; } return pre->val; } int main() { char str[15]; root=new node; memset(root,0,sizeof(node)); while(gets(str)&&strlen(str)) { Insert(str); } while(gets(str)) { printf("%d\n",Find(str)); } return 0; }
数组版,62MS
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define N 1000010 int sz; int val[N]; int ch[N][26]; void init() { sz=1; memset(ch[0],0,sizeof(ch[0])); } int getid(char ch) { return ch-‘a‘;} void Insert(char *s) { int pre=0,now; for(int i=0;s[i]!=‘\0‘;i++) { int id=getid(s[i]); now=ch[pre][id]; if(!now) { val[sz]=0; memset(ch[sz],0,sizeof(sz)); ch[pre][id]=sz; now=sz; sz++; } val[now]++; pre=now; } } int Find(char *s) { int pre=0,now; for(int i=0;s[i]!=‘\0‘;i++) { int id=getid(s[i]); now=ch[pre][id]; if(!now) return 0; pre=now; } return val[pre]; } int main() { char s[15]; init(); while(gets(s) && strlen(s)) { Insert(s); } while(gets(s)) { printf("%d\n",Find(s)); } return 0; }
标签:des style blog io ar color os sp java
原文地址:http://www.cnblogs.com/hate13/p/4119161.html