题目大意:现在有个长度已知的字符串,你知道一些它的子串,问你这个字符串的可能的种数(这些子串可以重叠),如果种数 <= 42,那么就把按照字典序输出来。
思路:先构造AC自动机,设 d[ u ][ len ][ st ]表示最后一个是 u ,已选长度为 len ,状态为 st 的剩余种数,则有方程:
d[ u ][ len ][ st ] = SIGMA(d[ ch[u][i] ][ len+1 ][ st|val[ch[u][i]] ], 0 <= i < SIGMA_SIZE)。这里有一点要注意,由于一个节点有可能是很多字符串的终点,AC自动机 insert
之后,在 get_fail 那里也要更新 val。输出结果那里,也是递归打印,不过有很重要的一个地方,那就是只有 d(u,len,st)> 0,才
递归下去!还有这里AC自动机要是改造版的那种,正好做 DP。
很好的一道题目啊,就是自己没想出来。。。= = ,这种字符串的题,我竟然没想到 AC自动机,题目都白做了,囧。。
思路:先构造AC自动机,设 d[ u ][ len ][ st ]表示最后一个是 u ,已选长度为 len ,状态为 st 的剩余种数,则有方程:
d[ u ][ len ][ st ] = SIGMA(d[ ch[u][i] ][ len+1 ][ st|val[ch[u][i]] ], 0 <= i < SIGMA_SIZE)。这里有一点要注意,由于一个节点有可能是很多字符串的终点,AC自动机 insert
之后,在 get_fail 那里也要更新 val。输出结果那里,也是递归打印,不过有很重要的一个地方,那就是只有 d(u,len,st)> 0,才
递归下去!还有这里AC自动机要是改造版的那种,正好做 DP。
很好的一道题目啊,就是自己没想出来。。。= = ,这种字符串的题,我竟然没想到 AC自动机,题目都白做了,囧。。
代码如下:
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long lld;
const int MAX_NODE = 11*11;
const int SIGMA_SIZE = 26;
int n,m;
lld d[MAX_NODE][33][1<<11];
bool vis[MAX_NODE][33][1<<11];
char ss[33];
int ch[MAX_NODE][SIGMA_SIZE];
int val[MAX_NODE];
int fail[MAX_NODE];
//int last[MAX_NODE];
struct AC
{
int tot;
void init()
{
tot = 1;
val[0] = 0;
memset(ch[0],0,sizeof(ch[0]));
}
int idx(char c)
{
return c - 'a';
}
void insert(char *s,int v)
{
int len = strlen(s);
int u = 0;
for(int i = 0;i<len;i++)
{
int c = idx(s[i]);
if(!ch[u][c])
{
val[tot] = 0;
memset(ch[tot],0,sizeof(ch[tot]));
ch[u][c] = tot++;
}
u = ch[u][c];
}
val[u] |= v;
}
void get_fail()
{
queue<int> q;
fail[0] = 0;
for(int i = 0;i<SIGMA_SIZE;i++)
{
int u = ch[0][i];
if(u)
{
q.push(u);
fail[u] = 0;
//last[0] = 0;
}
}
while(!q.empty())
{
int u = q.front();q.pop();
for(int i = 0;i<SIGMA_SIZE;i++)
{
int v = ch[u][i];
if(!v)
{
ch[u][i] = ch[fail[u]][i];//改造叶子节点
continue;
}
q.push(v);
int j = fail[u];
while(j && !ch[j][i])
j = fail[j];
fail[v] = ch[j][i];
val[v] |= val[fail[v]];
//last[v] = val[fail[v]] ? fail[v] : last[fail[v]];//后缀链接,指向j沿fail往回走遇到的下一个单词节点的编号
//printf("u = %d,v = %d,f = %d\n",u,v,fail[v]);
}
}
}
lld dfs(int u,int len,int st)
{
if(vis[u][len][st]) return d[u][len][st];
vis[u][len][st] = 1;
lld &ans = d[u][len][st];
if(len == n)
{
if(st == (1<<m)-1) return ans = 1;
else return ans = 0;
}
ans = 0;
for(int i = 0;i < SIGMA_SIZE;i++)
{
ans += dfs(ch[u][i],len+1,st|val[ch[u][i]]);
}
return ans;
}
void print(int u,int len,int st)
{
//printf("u = %d,len = %d,st = %d\n",u,len,st);
if(len == n)
{
for(int i = 1;i <= len;i++)
printf("%c",ss[i]);
puts("");
return ;
}
for(int i = 0;i < SIGMA_SIZE;i++)
{
ss[len+1] = i+'a';
if(d[ch[u][i]][len+1][st|val[ch[u][i]]])
print(ch[u][i],len+1,st|val[ch[u][i]]);
}
}
}ac;
char str[22];
int main()
{
int cas = 0;
while(~scanf("%d%d",&n,&m) && (n+m))
{
ac.init();
for(int i = 0;i < m;i++)
{
scanf("%s",str);
ac.insert(str,1<<i);
}
ac.get_fail();
memset(vis,0,sizeof(vis));
lld ans = ac.dfs(0,0,0);
printf("Case %d: %lld suspects\n",++cas,ans);
if(ans <= 42) ac.print(0,0,0);
}
return 0;
}