#include <stdio.h>
#include <string.h>
using namespace std;
#define lnt long long
const int N=114514;
struct node
{
char date;
int w;//以此字符结尾的字符串有几个
node *nx[64];
node(char x){date=x;w=0;memset(nx,0,sizeof(nx));}
};
struct trie
{
protected:
node *root;
char *p;int u;
inline int ys(char x){return x>='a'? x-'a'+36: (x>='A'? x-'A'+10: x-'0');}
void insert_sx(node *&cur)
{
if(cur==NULL){cur=new node(*p);}
cur->w+=1;
if(*(++p)!=0){insert_sx(cur->nx[ys(*p)]);}
}
void prefix_sx(node *cur)
{
if(cur==NULL){return;}
if(*(++p)==0){u+=cur->w;}
else{prefix_sx(cur->nx[ys(*p)]);}
}
void clear_sx(node *&cur)
{
for(int i=0;i<64;i++)
{if(cur->nx[i]!=NULL){clear_sx(cur->nx[i]);}}
delete cur;cur=NULL;
}
public:
inline void insert(char x[]){p=x;insert_sx(root->nx[ys(*p)]);}
inline int prefix(char x[]){p=x;u=0;prefix_sx(root->nx[ys(*p)]);return u;}
inline void clear(){clear_sx(root);}
inline void init(){root=new node(0);}
}t;
int G,n,m;
char a[N];
int main()
{
scanf("%d",&G);
while(G--)
{
scanf("%d%d",&n,&m);
t.init();
while(n--)
{
scanf("%s",a);
t.insert(a);
}
while(m--)
{
scanf("%s",a);
printf("%d\n",t.prefix(a));
}
t.clear();
}
return 0;
}
字典树容易看懂的指针写法
最新推荐文章于 2024-10-15 19:28:18 发布