题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题目思路:字典树模板题,上板子就行
板子链接传送门:https://blog.csdn.net/baodream/article/details/80685799
PS:这个题用指针始终会MLE,不知道为什么,网上的代码也会MLE,所以这个题就用数组过吧,QAQ。
代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define FOU(i,x,y) for(int i=x;i<=y;i++)
#define FOD(i,x,y) for(int i=x;i>=y;i--)
#define MEM(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)
const double EXP = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll MINF = 0x3f3f3f3f3f3f3f3f;
const double DINF = 0xffffffffffff;
const int mod = 1e9+7;
const int N = 1e6+5;
const int MAXN = 1000005; //数组第一维大小,字符串的个数*最大长度
struct DicTree{
int cnt[MAXN]; //代表某个前缀的单词总个数
int tree[MAXN][26];
int tot;
/*void init(){
//特别说明多组数据才用init,否则一般不用,因为这种多个字符串输入一般都是一组数据
MEM(cnt,0);
MEM(tree,0);
tot=0;
}*/
void Insert(char *s){
int len = strlen(s);
int now=0;
for(int i=0;i<len;i++){
int id = s[i]-'a';
if(!tree[now][id]){
tree[now][id] = ++tot;
}
now = tree[now][id];
cnt[now]++;
}
}
int Search(char *s){
int len=strlen(s);
int now=0;
for(int i=0;i<len;i++){
int id = s[i]-'a';
if(!tree[now][id])
return 0;
now=tree[now][id];
}
return cnt[now];
}
}dictree;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
std::ios::sync_with_stdio(false);
char s[20];
while(gets(s)){
if(s[0]=='\0')
break;
dictree.Insert(s);
}
while(gets(s))
{
printf("%d\n",dictree.Search(s));
}
return 0;
}