题意:给出许多个字符串;然后接下来再给出询问:
每一个询问都是一个字符串,问以这个字符串为前缀的单词有多少个;
这是字典树典型例题;
我们将题意给出的字符串建字典树,在建的时候,在每个节点位置都sum【x】++;
询问的时候:用单词跑一遍字典树,在跑到最后一个单词的节点的时候,返回此节点的sum即可
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxx = 400001; 4 char s[11]; 5 int trie[maxx][26],sum[maxx]; 6 int tot; 7 void Insert() 8 { 9 int rt=0; 10 for(int i=0;i<strlen(s);i++){ 11 int id=s[i]-'a'; 12 if(!trie[rt][id]) trie[rt][id]=++tot; 13 rt=trie[rt][id]; 14 sum[rt]++; //记录节点访问次数,即保存前缀 15 } 16 } 17 int Search() 18 { 19 int rt=0; 20 for(int i=0;i<strlen(s);i++){ 21 int id=s[i]-'a'; 22 if(!trie[rt][id]) return 0; 23 rt=trie[rt][id]; 24 } //rt经过此循环后变成前缀最后一个字母所在位置 25 return sum[rt]; //返回当前字符串结尾节点的访问次数,也就是作为前缀的出现次数 26 } 27 int main() 28 { 29 while(gets(s)&&s[0]!='\0')Insert(); 30 while(gets(s))printf("%d\n",Search()); 31 return 0; 32 }