不知道是我理解能力弱还是题意不清,最后的输出结果坑了我好长时间。这个题不要求去重的,给个数据吧
Sample Input
1
ab
1
abab
Sample Output
web 1: 1 1
total: 1
#include <iostream>
#include <cctype>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdio>
#include <cstdlib>
#define inf 0x3f3f3f3f
#define LL long long
#define maxn 1000005
#define For(i, a, b) for(int i = a; i <= b; i++)
#define Forx(i, a, b) for(int i = b; i >= a; i--)
#define Testin freopen("ztest.txt", "r", stdin)
#define Ansout freopen("zans.txt","w", stdout)
#define Memset(a) memset(a, 0, sizeof(a))
using namespace std;
struct Node{
int count;
Node* fail;
Node* next[131];
};
queue<Node*> que;
int ans[10000];
char str[1000000];
void insert(string str, Node* root, int k){
Node* p = root;
For(i, 0, str.size()-1){
int id = str[i];
if(p->next[id] == NULL){
Node* ne = (Node*) malloc (sizeof(Node));
ne->fail = NULL;
ne->count = -1;
For(j, 0, 130)
ne->next[j] = NULL;
p->next[id] = ne;
}
p = p->next[id];
}
p->count = k;
}
void build_ac(Node* root){
Node* p = root;
que.push(p);
while(!que.empty()){
Node* fr = que.front();
que.pop();
For(i, 0, 130){
if(fr->next[i] != NULL){
if(fr == root)
fr->next[i]->fail = root;
else{
Node* par = fr->fail;
while(par != NULL){
if(par->next[i] != NULL){
fr->next[i]->fail = par->next[i];
break;
}
par = par->fail;
}
if(par == NULL)
fr->next[i]->fail = root;
}
que.push(fr->next[i]);
}
}
}
}
int query(string text, Node* root){
int anss = 0;
Node* p = root;
For(i, 0, text.size()-1){
int id = text[i];
while(p != NULL && p->next[id] == NULL)
p = p->fail;
if(p != NULL)
p = p->next[id];
else
p = root;
Node* temp = p;
while(temp != root){
if(temp->count >= 0){
ans[anss++] = temp->count;
}
else
break;
temp = temp->fail;
}
}
return anss;
}
int main(){
//Testin;
int n;
while(scanf("%d", &n) == 1){
Node* root = (Node*) malloc (sizeof(Node));
For(i, 0, 130)
root->next[i] = 0;
root->fail = NULL;
For(i, 1, n){
cin >> str;
insert(str, root, i);
}
build_ac(root);
scanf("%d", &n);
int sum = 0;
For(i, 1, n){
Memset(ans);
cin >> str;
int num = query(str, root);
if(num){
sum++;
printf("web %d:", i);
sort(ans, ans+num);
For(j, 0, num-1) printf(" %d", ans[j]);
printf("\n");
}
}
printf("total: %d\n",sum);}
return 0;
}