http://acm.hdu.edu.cn/showproblem.php?pid=4287
分析:
赶脚这样的数据:
1 1
23
adsss
答案:0
效率比较(hash、字典树):
字典树(加了判断,是否为整个单词):
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int NM=5005;
char strn[NM][10],str[NM][10];
int map[30]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};
struct Node{
Node *next[10];
int ccount;
bool tail; //
Node(){
for(int i=0;i<10;i++)
next[i]=NULL;
ccount=0;
tail=false;
}
};
void BuildT(Node *tree,char *s1)
{
int i,len,t;
len=strlen(s1);
for(i=0;i<len;i++)
{
t=map[s1[i]-'a'];
if(tree->next[t]==NULL)
tree->next[t]=new Node();
tree=tree->next[t];
tree->ccount++;
}
tree->tail=true;
}
int SearchT(Node *tree,char *s2)
{
int i,len,t;
len=strlen(s2);
for(i=0;i<len;i++)
{
t=s2[i]-'0';
if(tree->next[t]!=NULL)
tree=tree->next[t];
else return 0;
}
if(tree->tail) return tree->ccount;
else return 0;
}
void DelT(Node *tree)
{
for(int i=0;i<10;i++)
if(tree->next[i]!=NULL)
DelT(tree->next[i]);
delete tree;
}
int main()
{
int i,n,m,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
Node *p=new Node();
for(i=0;i<n;i++)
scanf("%s",strn[i]);
for(i=0;i<m;i++)
{
scanf("%s",str[i]);
BuildT(p,str[i]);
}
for(i=0;i<n;i++)
printf("%d\n",SearchT(p,strn[i]));
DelT(p);
}
return 0;
}
哈希:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int NM=5005;
char str[NM][10];
int hash[1000005],a[NM];
int map[30]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};
int main()
{
int i,j,n,m,len,t,temp,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
memset(hash,0,sizeof(hash));
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<m;i++)
{
scanf("%s",str[i]);
len=strlen(str[i]);
temp=0;
for(j=0;j<len;j++)
{
t=map[str[i][j]-'a'];
temp=temp*10+t;
}
hash[temp]++;
}
for(i=0;i<n;i++)
printf("%d\n",hash[a[i]]);
}
return 0;
}