syhd142  
日历
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
统计
  • 随笔 - 23
  • 文章 - 122
  • 评论 - 31
  • 引用 - 0

导航

常用链接

留言簿(2)

随笔档案(23)

文章分类(270)

文章档案(122)

我的豆瓣

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 
模板题
#include <stdio.h>
#include 
<string.h>
#include 
<math.h>
#include 
<queue>

#define KIND 26
#define N 1005
#define M 2000005

struct node
{
    node 
*fail;
    node 
*next[KIND];
    
int id;
    node ()
        {
            fail 
= NULL;
            id 
= 0;
            memset(next, 
0sizeof(next));
        }
};

char ch[M], key[N][55];
int count[N];

void insert(node *&root, char *ch, int num)
{
    node 
*= root;
    
int i = 0, t;
    
while(ch[i])
    {
        t 
= ch[i] - 'A';
        
if(!p->next[t]) p->next[t] = new node();
        p 
= p->next[t];
        i
++;
    }
    p
->id = num;
}

void AC(node *&root)
{
    std::queue
<node *> q;
    q.push(root);
    
while(!q.empty())
    {
        node 
*= NULL;
        node 
*= q.front();
        q.pop();
        
for(int i = 0; i < KIND; i++)
        {
            
if(t->next[i])
            {
                p 
= t->fail;
                
while(p)
                {
                    
if(p->next[i])
                    {
                        t
->next[i]->fail = p->next[i];
                        
break;
                    }
                    p 
= p->fail;
                }
                
if(!p) t->next[i]->fail = root;
                q.push(t
->next[i]);
           }
        }
    }
}

void query(node *&root, char *ch)
{
    
int i = 0, t;
    node 
*= root, *tmp;
    
while(ch[i])
    {
        
if(ch[i] > 'Z' || ch[i] < 'A')
        {
            p 
= root;
            i
++;
            
continue;
        }
        t 
= ch[i] - 'A';
        
while(!p->next[t] && p != root) p = p->fail;
        p 
= p->next[t];
        
if(!p) p = root;
        tmp 
= p;
        
while(tmp != root)
        {
            count[tmp
->id]++;
            tmp 
= tmp->fail;
        }
        i
++;
    }
}

int main()
{
    
int n;
    
while(~scanf("%d"&n))
    {
        node 
*root = new node();
        memset(count, 
0sizeof(count));
        
for(int i = 1; i <= n; i++)
        {
            scanf(
"%s", key[i]);
            insert(root, key[i], i);
        }
        AC(root);
        scanf(
"%s", ch);
        query(root, ch);
        
for(int i = 1; i <= n; i++)
        {
            
if(count[i])
            {
                printf(
"%s: %d\n", key[i], count[i]);
            }
        }
    }
    
return 0;
}
posted on 2011-01-10 15:58 Fucker 阅读(469) 评论(0)  编辑 收藏 引用 所属分类: ACM/ICPC字符串

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


 
Copyright © Fucker Powered by: 博客园 模板提供:沪江博客