给n个单词建立一个表
给n个串
查询以该串为前缀的单词个数 包括本身
就是单纯地遍历一次字典树
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <vector>
using namespace std;
#define inf 2147483647
const int maxnode = 400110;
int len;
struct trie
{
int ch[maxnode][26];
int val[maxnode];
int sz;
void init()
{
sz=1;
val[0]=0; //可不需要
memset(ch[0],0,sizeof(ch[0]));
}
int idx(char c) {return c-'a';}
void insert(char *s )
{
int u=0,n=strlen(s),i;
for (i=0;i<n;i++)
{
int c=idx(s[i]);
if (!ch[u][c])
{
memset(ch[sz],0,sizeof(ch[sz]));
val[sz]=0;
ch[u][c]=sz++;
}
u=ch[u][c];
val[u]++;
}
}
int query_if(char *s) //查找当前单词是否存在,本题用不上
{
int u=0,n=strlen(s),i;
for (i=0;i<n;i++)
{
int c=idx(s[i]);
if (!ch[u][c])
return 0;
else
{
u=ch[u][c];
}
}
return val[u];
}
};
trie tp;
char tm[15];
int main()
{
tp.init();
while( gets(tm))
{
if (tm[0]==0)
break;
tp.insert(tm);
}
while( scanf("%s", &tm)!=EOF)
{
printf("%d\n",tp.query_if(tm ));
}
return 0;
}