您的位置:首页 > 其它

hdu 3065 病毒侵袭持续中 DFA 求字符串最多匹配多少字符串 每个子串最多匹配多少个

2011-04-22 19:06 417 查看
#include<iostream>

#include<cstdio>

#include<cstring>

#include<string>

#include<queue>

#include<cctype>

#include<algorithm>

using namespace std;

//DFA 求字符串最多匹配多少字符串 每个子串最多匹配多少个

const int maxn=2100000;

struct Node

{

int num;//序号

Node *next[27];//后继指针

Node* fail;//失败指针

/*指向树中出现过的S的最长的后缀,换句话说就是在前缀集中出现的最长的S的后缀.*/

};

//字典树

Node temp[maxn];

int tp;

//.........

int n;//字符串个数

Node *root;//头指针

char mat[1100][55];//模式串 各不相同

int cont[1100];//模式串在主串中出现次数

void reset(Node* rot)

{

rot->num=0;

for(int i=0;i<27;i++) rot->next[i]=NULL;

rot->fail=root;//important

if(rot==root) rot->fail=NULL;//important

}

//初始化

void init()

{

memset(cont,0,sizeof(cont));

tp=0;

root=&temp[tp++];

reset(root);

}

//插入字典树

void insert(char *word,int index)

{

Node *p=root;

for(int i=0;word[i];i++)

{

int x;

if(isupper(word[i])) x=word[i]-'A';

else x=26;

if(p->next[x]==NULL)

{

p->next[x]=&temp[tp++];

reset(p->next[x]);

}

p=p->next[x];

}

p->num=index;

}

//构造失败指针

Node *que[maxn*4];

int front,rear;

void DFA()

{

Node* p=root;

front=rear=0;

que[rear++]=p;

while(front<rear)

{

Node* t=que[front++];

for(int i=0;i<27;i++)

{

Node* cnt=t->next[i];

if(cnt!=NULL)

{

Node* fath=t->fail;

while(fath!=NULL&&fath->next[i]==NULL)

{

fath=fath->fail;

}

if(fath!=NULL)

{

cnt->fail=fath->next[i];

}

else

{

cnt->fail=p;//important

}

que[rear++]=cnt;

}

}

}

}

//查看str最多匹配多少字符串 每个子串最多匹配多少个

void find(char* str)

{

Node* p=root;

Node* fath;

Node* cnt;

for(int i=0;str[i];i++)

{

int x;

if(isupper(str[i])) x=str[i]-'A';

else x=26;

cnt=p->next[x];

if(cnt!=NULL)

{

for(fath=cnt;fath!=NULL;fath=fath->fail)

{

if(fath->num)

{

cont[fath->num]++;

}

}

p=cnt;

}

else

{

fath=p->fail;

while(fath!=NULL&&fath->next[x]==NULL)

{

fath=fath->fail;

}

if(fath!=NULL)

{

cnt=fath->next[x];

for(fath=cnt;fath!=NULL;fath=fath->fail)

{

if(fath->num)

{

cont[fath->num]++;

}

}

p=cnt;

}

else

{

p=root;

}

}

}

}

char str[maxn];

int main()

{

while(scanf("%d ",&n)==1)

{

init();//初始化

for(int i=1;i<=n;i++)

{

gets(mat[i]);

memcpy(str,mat[i],sizeof(mat[i]));

insert(str,i);//在字典树上插入字符串

}

DFA();//构造失败指针

gets(str);//主串

find(str);

for(int i=1;i<=n;i++)

{

if(cont[i]) printf("%s: %d/n",mat[i],cont[i]);

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: