标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 34924 Accepted Submission(s): 13112
#include <cstdio> #include <cstring> const int MAX = 26; struct Node{ Node* pt[MAX]; int num; }; Node *root; Node memory[500000]; int allo = 0; void trie_init() { root = new Node; memset(root->pt, NULL, sizeof(root->pt)); } void trie_insert(char str[]) { Node *p = root, *q; for(int i = 0; str[i] != ‘\0‘; ++i){ int id = str[i]-‘a‘; if(p->pt[id] == NULL){ q = &memory[allo++]; memset(q->pt, NULL, sizeof(q->pt)); q->num = 1; p->pt[id] = q; } else{ ++p->pt[id]->num; } p = p->pt[id]; } } int trie_find(char str[]) { Node *p = root; for(int i = 0; str[i] != ‘\0‘; ++i){ int id = str[i]-‘a‘; if(p->pt[id] == NULL){ return 0; } p = p->pt[id]; } return p->num; } int main() { char s[15]; trie_init(); while(gets(s) && s[0]){ trie_insert(s); } while(gets(s)){ printf("%d\n", trie_find(s)); } return 0; }
用map很耗时,但本题刚好可以卡过去。
#include <cstdio> #include <string> #include <cstring> #include <map> using namespace std; map<string, int> mp; int main() { char s[15]; while(gets(s) && s[0]){ int len = strlen(s); for(int i = len; i > 0; --i){ s[i] = ‘\0‘; ++mp[s]; } } while(gets(s)){ printf("%d\n", mp[s]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/inmoonlight/p/5906532.html