题目链接
开动态字典树外带内存释放,卡过C++,再多一丢丢都要MLE的那种哦……还是很爽的!
这道题与这一道题不同就不同在不能去减,能用的就都要用上,然后就直接输出就是了,美滋滋……一开始还是写错了些,忘记给used[]数组初始化,然后有些地方没有写上"->fail",然后找了两个小时BUG,最后,惊险!过了,就好。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
int N, M;
char virus[205];
struct node
{
node * next[128];
node * fail;
int sum, id;
};
node *root, *new_node;
void update(char *s, int id)
{
node *temp = root;
int len = (int)strlen(s);
for(int i=0; i<len; i++)
{
int x = s[i];
if(temp->next[x] == NULL)
{
new_node = (node *)malloc(sizeof(node));
for(int i=0; i<128; i++) new_node->next[i] = NULL;
new_node->fail = NULL;
new_node->sum = 0;
temp->next[x] = new_node;
}
temp = temp->next[x];
}
temp->sum++;
temp->id = id;
}
void build_fail()
{
queue<node *> Q;
Q.push(root);
node *temp, *p;
while(!Q.empty())
{
temp = Q.front(); Q.pop();
for(int i=0; i<128; i++)
{
if(temp->next[i])
{
if(temp == root) temp->next[i]->fail = root;
else
{
p = temp->fail;
while(p)
{
if(p->next[i]) { temp->next[i]->fail = p->next[i]; break; }
p = p->fail;
}
if(!p) temp->next[i]->fail = root;
}
Q.push(temp->next[i]);
}
}
}
}
const int maxN = 1e4 + 5;
char ques[maxN];
bool used[505];
bool AC_auto(char *s, int id)
{
memset(used, false, sizeof(used));
bool flag = false;
node *p = root, *temp;
int len = (int)strlen(s);
for(int i=0; i<len; i++)
{
int x = s[i];
while(p != root && !p->next[x]) p = p->fail;
p = p->next[x];
if(p == NULL) p =root;
temp = p;
while(temp != root)
{
if(temp->sum)
{
flag = true;
used[temp->id] = true;
}
temp = temp->fail;
}
}
if(!flag) return false;
printf("web %d:", id);
for(int i=1; i<=N; i++) if(used[i]) printf(" %d", i);
printf("\n");
return true;
}
inline void init()
{
root = (node * )malloc(sizeof(node));
for(int i=0; i<128; i++) root->next[i] = NULL;
root->fail = NULL;
root->sum = 0;
}
inline void FREE(node *temp)
{
for(int i=0; i<128; i++) if(temp->next[i]) FREE(temp->next[i]);
delete(temp);
}
int main()
{
while(scanf("%d", &N)!=EOF)
{
init();
for(int i=1; i<=N; i++)
{
scanf("%s", virus);
update(virus, i);
}
build_fail();
scanf("%d", &M);
int cnt = 0;
for(int i=1; i<=M; i++)
{
scanf("%s", ques);
if(AC_auto(ques, i)) cnt++;
}
printf("total: %d\n", cnt);
FREE(root);
}
return 0;
}