题目:http://acm.hdu.edu.cn/showproblem.php?pid=3065
每个子串是不同的,求出在源码串中各个子串出现的次数,按照输入子串的顺序将出现次数大于0的输出。
例如:
Sample Input
3 AA BB CC ooxxCC%dAAAoen....END
Sample Output
AA: 2 CC: 1HintHit: 题目描述中没有被提及的所有情况都应该进行考虑。比如两个病毒特征码可能有相互包含或者有重叠的特征码段。 计数策略也可一定程度上从Sample中推测。
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int head,tail;
const int nn=60; //122-65=57
int N;
char str[2000010],keyword[55];
char s[1000][55];
struct node{
int sum,id;
node *next[nn],*fail;
bool operator <(const node other)const {
return id>other.id;
}
node(){ //inital node
fail=NULL;
id=sum=0;
memset(next,0,sizeof(next)); //here
}
}*q[55*1000];
node *root;
void insert_t(char str[],int dex){
int temp,len;
node *p=root;
len=strlen(str);
for(int i=0;i<len;i++){
temp=str[i]-65;
if(p->next[temp]==NULL)p->next[temp]=new node();
p=p->next[temp];
}
p->id=dex;
strcpy(s[dex],str);
p->sum++;
}
void build_ac(){ //inital fail point
q[tail++]=root;
while(head<tail){
node *p=q[head++],*temp=NULL;
for(int i=0;i<nn;i++){
if(p->next[i]!=NULL){
if(p==root)p->next[i]->fail=root;
else {
temp=p->fail;
while(temp){
if(temp->next[i]){
p->next[i]->fail=temp->next[i];
break;
}
temp=temp->fail;
}
if(!temp)p->next[i]->fail=root;
}
q[tail++]=p->next[i];
}
}
}
}
priority_queue<node> que;
void query(){
int i,dex,len=strlen(str);
node *p=root;
for(i=0;i<len;i++){
dex=str[i]-65;
if(dex<0||dex>57){
p=root;
continue;
}
while(p->next[dex]==NULL&&p!=root)p=p->fail;
p=p->next[dex];
if(!p)p=root;
node *temp=p;
while(temp!=root&&temp->sum!=0){
que.push(*temp);
temp=temp->fail;
}
}
}
int main()
{
int t;
while(cin>>N){
head=tail=0;
root=new node();
int i,j,total=0;
for(i=0;i<N;i++){
scanf("%s",keyword);
insert_t(keyword,i+1);
}
build_ac();
scanf("%s",str);
query();
while(!que.empty()){
node temp1=que.top();
que.pop();
if(!que.empty()){
node temp2=que.top();
//que.pop();
while(temp1.id==temp2.id){
temp2.sum+=temp1.sum; //处理sum
temp1=temp2;
que.pop();
if(!que.empty()){
temp2=que.top();
}
else break;
}
}
printf("%s: %d\n",s[temp1.id],temp1.sum);
}
}
return 0;
}