PS: 每每學到一個知識點,要多多練習知道非常熟悉,信手拈來, 以後多多練習一下強大的指針操作。
此題目開內存蠻大的。
#include#include #include #include using namespace std; struct Trie { Trie* next[26]; int num; }; //Accepted 1251 78MS 43796K 1182 B C++ Achiber Trie* root; void Insert(char *str) { Trie* now = root; int len = strlen(str); for(int i = 0; i < len; i++) { int id = str[i]-'a'; if(now->next[id]==NULL) { Trie* p = new Trie; p->num = 0; memset(p->next, NULL, sizeof(p->next)); now->next[id] = p; } now = now->next[id]; now->num++; } } int query(char* str) { Trie* now = root; int counter = 0; int len = strlen(str); for(int i = 0; i < len; i++) { int id = str[i]-'a'; if(now->next[id]==NULL) { return 0; } else { now = now->next[id]; counter = now->num; } } return counter; } int main() { root = new Trie; memset(root->next, NULL, sizeof(root->next)); char str[20]; while(gets(str) && str[0]) Insert(str); while(gets(str)) { int res = query(str); printf("%d\n", res); } return 0; }