hdu Repository(字典树)

Problem Description
When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
 

Input
There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
 

Output
For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
 

Sample Input
  
  
20 ad ae af ag ah ai aj ak al ads add ade adf adg adh adi adj adk adl aes 5 b a d ad s
 

Sample Output
  
  
0 20 11 11 2
这题搞的我很蛋疼,好不容易把数据过了,又MLE和RE了数次。。。。刚开始写字典树。。。。还是忍了!!!
题意很简单,查询单词是否存在于上面的所有单词中,输出存在的单词数。这题需要枚举单词的每个字母作为起点,每个字母建成一棵树,所以内存需要开很大。
代码:
#include<stdio.h>
#include<string.h>
const int N=500005;
int n,m,cnt=1,cur;
char str[30];
struct node
{
    int p[26];
    int flag;
    int last;
} tree[N];
void build(char *s,int cur)
{
   int p=0;
   while(*s)
   {
      if(tree[p].p[*s-'a']==-1)
         tree[p].p[*s-'a']=cnt++;
      p=tree[p].p[*s-'a'];
      if(tree[p].last!=cur)  //这里一个串可能有几个相同的子串,需要标记一下,比如ababab查询到ab出现了3次,但只能算一次
      {
        tree[p].last=cur;
        tree[p].flag++;
      }
      s++;
   }
}

int find(char *s)
{
   int p=0;
   while(*s)
   {
      if(tree[p].p[*s-'a']==-1)
          return 0;
      p=tree[p].p[*s-'a'];
      s++;
   }
   return tree[p].flag;
}
int main()
{
  int n,i,m,num;
  for(i=0;i<N;i++) 
  {
     tree[i].flag=0;
     tree[i].last=-1;
     memset(tree[i].p,-1,sizeof(tree[i].p));
  }
  scanf("%d",&n);
  for(cur=0;cur<n;cur++)
  {   
       scanf("%s",str);
      for(i=0;i<=strlen(str);i++)
          build(str+i,cur);
  }
   scanf("%d",&m);
   while(m--)
   {   
       scanf("%s",str);
       printf("%d\n",find(str));
   }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值