hdu 2222 AC自动机 (二)

2014-11-24 03:07:10 · 作者: · 浏览: 3
01],p[55] ;
//结点结构
struct Node
{
int cnt ;
Node *fail ;
Node *next[26] ;
};
Node *root = new Node ;
//初始化结点
void init(Node *t)
{
memset(t->next,NULL,sizeof(t->next)) ;
t->cnt = 0 ;
t->fail = NULL ;
}
//插入新单词
void insert(char *str)
{
int i=0,k ;
Node *p = root ;
Node *newnode ;
while(str[i]){ //若用 for(i=0;i k = str[i] - 'a' ;
if(p->next[k] == NULL){
newnode = new Node ;
init(newnode) ;
p->next[k] = newnode ;
p = newnode ;
}
else{
p = p->next[k] ;
}
i++;
}
p->cnt ++;
}
//确定fail指针
void makeFail()
{
Node *front ;
queueq ;
q.push(root) ;
while(!q.empty()){
front = q.front() ;
q.pop() ;
for(int i = 0;i < 26;i++){
if(front->next[i] != NULL){ //父结点有孩子i,则找孩子i的fail指针
if(front == root)
front->next[i]->fail = root ;//与根结点相连的结点的fail指针都指向根结点
else{
Node *temp = front ;
while(temp->fail != NULL){ //父结点fail指针非空
if(temp->fail->next[i] != NULL){ //父结点fail指针指向的结点有孩子i
front->next[i]->fail = temp->fail->next[i] ;
break ;
}
temp = temp->fail ;//父结点向上转移
}
if(temp->fail == NULL)
front->next[i]->fail = root ;
}
q.push(front->next[i]) ;//找到孩子i的fail指针后将孩子i加入队列
}
}
}
}
//在文章中搜索单词
int search(char *str)
{
Node *p = root ;
Node *temp = NULL ;
int i=0,k,ans = 0 ;
while(str[i]){
k=str[i] - 'a' ;
while(p != root && p->next[k] == NULL){
p = p->fail ;
}
if(p->next[k] != NULL){//p记录当前位置最长的后缀匹配,下次从该支继续匹配
p = p->next[k] ;
temp = p ; //用temp继续找当前位置较短的后缀匹配
while(temp != root && temp->cnt != -1){
ans += temp->cnt ;//注意一定是+=,而不能直接++,因为cnt可能为0
temp->cnt = -1 ;
temp = temp->fail ;
}
}
i++;
}
return ans ;
}
//释放内存
void freedom(Node *p)
{
for(int i = 0;i < 26;i++){
if(p->next[i] != NULL)
freedom(p->next[i]) ;
}
delete p ;
}
int main()
{
int t,k,i,ans ;
scanf("%d",&t) ;
while(t--){
init(root) ;
scanf("%d",&k) ;
getchar();
while(k--){
gets(p) ;
insert(p) ;
}
makeFail() ;
gets(s) ;
ans = search(s) ;
printf("%d\n",ans) ;
for(i = 0;i < 26;i ++){//注意root不能删除
if(root->next[i] != NULL)
freedom(root->next[i]) ;
}
}
delete root ;
return 0 ;
}