链接:http://acm.hdu.edu.cn/showproblem.php?pid=4287
解题思路:
先把单词化成数字插入到字典树,然后查询次数.
AC code:
#include <iostream>
#include<cstring>
using namespace std;
#define N 5005
char num[N][7]; //数字
char str[7]; //字母
struct node
{
int count;
node *next[10]; //小标范围最大值为9
};
void Insert(node *&root,char str[])
{
int i=0,len=strlen(str);
node *current=new node;
current=root;
while (i<len)
{
if(current->next[str[i]-'0']!=NULL)
current=current->next[str[i]-'0'];
else
{
node *newnode=new node;
newnode->count=0;
for(int j=0;j<10;++j) newnode->next[j]=NULL;
current->next[str[i]-'0']=newnode;
current=newnode;
}
if(i==len-1) current->count+=1;
i++;
}
}
int Search(node *root,char str[])
{
int i=0,len=strlen(str);
while (i<len)
{
if(root->next[str[i]-'0']==NULL)
return 0;
else
{
root=root->next[str[i]-'0'];
}
if(i==len-1) return root->count;
i++;
}
}
int main()
{
int test,n,m,i,j,k;
cin>>test;
while (test--)
{
cin>>n>>m;
memset(num,0,sizeof(num));
memset(str,0,sizeof(str));
for(i=0;i<n;++i)
cin>>num[i];
node *root=new node;
root->count=0;
for(j=0;j<10;++j) root->next[j]=NULL;
for(j=0;j<m;++j)
{
cin>>str;
for(k=0;k<strlen(str);++k)
{
if(str[k]=='a'||str[k]=='b'||str[k]=='c') str[k]='2';
else if(str[k]=='d'||str[k]=='e'||str[k]=='f') str[k]='3';
else if(str[k]=='g'||str[k]=='h'||str[k]=='i') str[k]='4';
else if(str[k]=='j'||str[k]=='k'||str[k]=='l') str[k]='5';
else if(str[k]=='m'||str[k]=='n'||str[k]=='o') str[k]='6';
else if(str[k]=='p'||str[k]=='q'||str[k]=='r'||str[k]=='s') str[k]='7';
else if(str[k]=='t'||str[k]=='u'||str[k]=='v') str[k]='8';
else if(str[k]=='w'||str[k]=='x'||str[k]=='y'||str[k]=='z') str[k]='9';
}
Insert(root,str);
}
for(i=0;i<n;++i)
cout<<Search(root,num[i])<<endl;
}
}