PS: 每每学到一个知识点,要多多练习知道非常熟悉,信手拈来, 以后多多练习一下强大的指针操作。
此题目开内存蛮大的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
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;
}