hdu 2846 Repository
字典树。字典树可以很快的算出某个前缀出现的次数,所以以每个字母作为起点,都插入到字典树中,单词的某一前缀只加一次,加一次之后标记掉,之后不再加。
由于之前没有考虑到查询的单词在字典树中没有出现,导致RE了N次。。。
#include<cstdio> #include<cstring> #include<cmath> #include<string> #include<algorithm> using namespace std; struct shu{ int summ, nn[27], jihao; }node[500005]; int n, i, j, k, ii, tott, zz, q; char s[25], ls[25]; int main() { while (~scanf("%d", &n)) { tott = 1; for (i = 0; i < 500005-5; i++) { memset(node[i].nn, -1, sizeof(node[i].nn)); node[i].summ = 0; node[i].jihao = -1; } for (ii = 0; ii < n; ii++) { scanf("%s", s); int len = strlen(s); for (i = 0; i < len; i++) { zz = 0; for (j = i; s[j]; j++) { if (node[zz].nn[s[j] - 'a'] == -1) { node[zz].nn[s[j] - 'a'] = tott; tott++; } zz = node[zz].nn[s[j] - 'a']; if (node[zz].jihao != ii) { node[zz].summ++; node[zz].jihao = ii; } } } } scanf("%d", &q); for (ii = 0; ii < q; ii++) { int shuchu = 0; scanf("%s", s); zz = 0; for (i = 0; s[i]; i++) { zz = node[zz].nn[s[i] - 'a']; if (zz == -1) { printf("%d\n", 0); shuchu = 1; break; } } if(!shuchu) printf("%d\n", node[zz].summ); } } return 0; }