您的位置:首页 > 其它

light oj 1427(ac自动机)

2016-07-31 15:52 295 查看
#include <bits/stdc++.h>

using namespace std;

const int N = 510*505;
const int M = 27;

map<string,int>Map;
struct Trie
{
int next
[M],fail
,end
;
int root,L;
int newnode()
{
for(int i = 0; i < 26; i++)
next[L][i] = -1;
end[L++] = -1;
return L - 1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(string s,int id)
{
int len = s.size();
int now = root;
for(int i = 0; i < len; i++)
{
if(next[now][s[i]-'a'] == -1)
next[now][s[i] - 'a'] = newnode();
now = next[now][s[i] - 'a'];
}
end[now] = id;
}
void build()
{
queue<int>Q;
fail[root] = root;
for(int i = 0; i < 26; i++)
{
if(next[root][i] == -1)
next[root][i] = root;
else
{
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
}
while(!Q.empty())
{
int now = Q.front();
Q.pop();
for(int i = 0; i < 26; i++)
{
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
int num[1000];
void query(char buf[],int n,int mm[])
{
for(int i = 1; i <= n; i++)
num[i] = 0;
int len = (int)strlen(buf);
int now = root;
for(int i = 0; i < len; i++)
{
now = next[now][buf[i]-'a'];
int temp = now;
while( temp != root )
{
if( end[temp] != -1)
num[end[temp]]++;
temp = fail[temp];
}
}
for(int i = 1; i <= n; i++)
printf("%d\n",num[mm[i]]);
}
};

char buf[1000100];
Trie ac;

void solve()
{
ac.init();
int n, l = 0;
scanf("%d",&n);
scanf("%s",buf);
Map.clear();
int twice[1005];
memset(twice,0,sizeof(twice));
for(int i = 1; i <= n; i++)
{
string ss;
cin>>ss;
int c = Map[ss];
if(c == 0)
{
Map[ss] = ++l;
ac.insert(ss,l);
}
twice[i] = Map[ss];
//int tmp = Map[ss];

}
ac.build();

ac.query(buf,n,twice);
}

int main(void)
{
int t,cnt = 0;
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",++cnt);
solve();
}

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