hdu 3065 分类: hdu 2015-04-02 19:11 33人阅读 评论(0) 收藏


多组数据会卡动态空间,即使是中途释放空间也无济于事。。。


#include<map>
#include<string>
#include<queue>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>

const int MAXN =  1005, MAXL = 55, MAXS = 2000005;

int n; 
struct TireNode{int p[26],fail; int end;}b[MAXN*MAXL] = {0},emp = {{0},0,0};
char s[MAXN][MAXL] = {'\0'};int root, blen = 0;

int newnode(){ b[++blen] = emp; return blen;}

void Insert(int id,char str[])
{
     int tmp = root;
     int sl = strlen(str);
     for(int j = 0; j < sl; j++)
     {
        if(!b[tmp].p[str[j]-'A'])
          b[tmp].p[str[j]-'A'] = newnode();
        tmp = b[tmp].p[str[j]-'A'];  
     }
     b[tmp].end = id; 
}
void TireBuild() 
{  
    blen = 0;root = newnode(); 
    for(int i = 1; i <= n; i++)
    {
        scanf("%s",s[i]);   
        Insert(i,s[i]);
    }
}
void acBuild()
{   
    std::queue<int>line;

    b[root].fail = root;
    for(int i = 0; i < 26; i++)
      if(!b[root].p[i])b[root].p[i] = root;
      else  
      { 
       b[b[root].p[i]].fail = root;
       line.push(b[root].p[i]); 
      }

    while(!line.empty())
    {
        int now = line.front();
        line.pop();
        for(int i = 0; i < 26;i++)
          if(!b[now].p[i])
            b[now].p[i] = b[b[now].fail].p[i];
          else
          { 
            b[b[now].p[i]].fail = b[b[now].fail].p[i];
            line.push(b[now].p[i]);
          }
    }
}
void query(int cnt[],char str[])
{
    int len = strlen(str);
    int now = root, tmp;

    for(int i = 0 ;i < len ;i++)
      if(str[i] >= 'A' && str[i] <= 'Z')
     {
       now = b[now].p[str[i]-'A'];

       tmp = now;
       while(tmp != root)
       {
          cnt[b[tmp].end]++;
          tmp = b[tmp].fail;
       }
     }
      else now = root;

}
int main()
{ 
#ifndef ONLINE_JUDGE
    freopen("hdu3065.in","r",stdin);
    freopen("hdu3065.out","w",stdout);
#endif

    while(scanf("%d",&n)!=EOF)
    {
     int sum = 0 ,T;
     static char mus[MAXS];
     static int ans[MAXN];

     TireBuild();
     acBuild();

     memset(ans,0,sizeof(ans));
     scanf("%s",mus);
     query(ans,mus);

     for(int i = 1; i <= n;i++)
        if(ans[i])printf("%s: %d\n",s[i],ans[i]);
    }

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-04-02 19:11  <Dash>  阅读(125)  评论(0编辑  收藏  举报