题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6208
题目意思:
给出N个字符串,从中挑选出一个字符串,使其他所有N个字符串都是其子串。
如果这个串不存在输出No,否则输出这个串。
解题思路:
AC自动机入门级题目,对N个字符串构建字典树,然后选取N个字符串中长度最长
的那个(当然长度最长的可能有多个)但是不用管,存在多个的时候,随便选一个
就可以了,最后让这个字符串在AC自动机上跑以下,如果匹配到的单词个数是N,
就输出这个单词,否则输出No.
AC代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int maxn = 1000010;
const int allSon = 26;
char text[maxn]; ///文本串
char str[maxn];
int node[maxn][allSon]; ///字典树节点
int fail[maxn]; ///fail指针
int num[maxn]; ///num[i]代表以第i个节点为结尾的单词个数
int id; ///用来给节点编号
int ans;
void insertPatten()
{
int p = 0; ///指向根节点
int pos = 0; ///下标
int len = strlen(str);
while(pos < len)
{
int ch = str[pos]-'a';
if(node[p][ch] == -1) ///节点不存在
{
memset(node[id],-1,sizeof(node[id])); ///孩子节点都置为空
num[id] = 0;
fail[id] = -1;
node[p][ch] = id++;
}
p = node[p][ch];
pos++;
}
num[p]++;
}
void build_AC_automaton()
{
queue<int>qu;
int p = 0;
qu.push(p);
while(!qu.empty())
{
p = qu.front();
qu.pop();
for(int i = 0; i < allSon; i++)
{
if(node[p][i] != -1) ///第i个孩子存在
{
if(p == 0) ///如果p是根,根的孩子fail指向根
{
fail[node[p][i]] = 0;
}
else
{
int temp = fail[p];
while(temp != -1)
{
if(node[temp][i] != -1)
{
fail[node[p][i]] = node[temp][i];
break;
}
temp = fail[temp];
}
if(temp == -1)
{
fail[node[p][i]] = 0;
}
}
qu.push(node[p][i]);
}
}
}
}
void find_in_AC_automaton()
{
ans = 0;
int p = 0;
int pos = 0;
int len = strlen(text);
while(pos < len)
{
int ch = text[pos]-'a';
while(node[p][ch]==-1 && p != 0)
p = fail[p];
p = node[p][ch];
if(p == -1) p = 0;
int temp = p;
while(temp != 0 && num[temp]!=-1)
{
ans += num[temp];
num[temp] = -1;
temp = fail[temp];
}
pos++;
}
}
void init()
{
memset(node[0],-1,sizeof(node[0]));
num[0] = 0;
fail[0] = -1;
id = 1;
}
int main()
{
int T,N;
scanf("%d",&T);
while(T--)
{
scanf("%d",&N);
strcpy(text,"");
init();
int temp = N;
while(N--)
{
scanf("%s",str);
if(strlen(text)<strlen(str))
{
strcpy(text,str);
}
insertPatten();
}
build_AC_automaton();
find_in_AC_automaton();
if(temp == ans)
printf("%s\n",text);
else
printf("No\n");
}
return 0;
}