HDU 1251 統計難題-字典樹
阿新 • • 發佈:2019-01-24
友情題目連結http://acm.hdu.edu.cn/showproblem.php?pid=1251
基礎字典樹:
#include<cstdio> #include<cstring> char s[15]; struct node { int cnt; node *next[26]; void init() //初始化 { cnt=0; for(int i=0;i<26;i++) { next[i]=NULL; } } } ; void insert(node *root,char *s) { node *p=root; for(int i=0;s[i];i++) { int t=s[i]-'a'; if(p->next[t]==NULL) { p->next[t]=new node; p=p->next[t]; p->init() ; } else p=p->next[t]; p->cnt++; } } int find(node *root, char *s) { node *p=root; for(int i=0;s[i];i++) { int t=s[i]-'a'; p=p->next[t]; if(!p) return 0; } return p->cnt; } int main() { node *root=new node(); root->init() ; while(gets(s)&&strlen(s))//輸入控制!!! { insert(root,s); } while(gets(s)) { printf("%d\n",find(root,s)); } return 0; }
大神程式碼,簡單,但注意容易超時!!
#include<cstdio> #include<string> #include<map> #include<cstring> #include<iostream> using namespace std; int main() { char str[11]; map<string, int> F; while(gets(str)) { int len = strlen(str); if( !len ) break; for(int i = len; i > 0; --i) { str[i] = '\0'; F[str]++; } } while(gets(str)) cout << F[str] << endl; return 0; }