题意
传送门 P4584 [FJOI2015]带子串包含约束LCS问题
题解
分别对 X , Y X,Y X,Y 建序列自动机,那么可以从根节点搜索以遍历所有的公共子序列。对约束集子串建 A C AC AC 自动机,搜索的同时更新子序列后缀状态。对约束集子串进行状态压缩,在 A C AC AC 自动机 B F S BFS BFS 计算失配指针时,将各个节点对应的后缀状态记录所有的等于约束子集的后缀。最后 S P F A SPFA SPFA 求解最长子序列。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <map>
#include <queue>
using namespace std;
#define maxk 6
#define maxc 58
#define maxn 301
struct node
{
int x, y, p, s;
bool operator<(const node &b) const
{
if (x != b.x)
return x < b.x;
if (y != b.y)
return y < b.y;
if (p != b.p)
return p < b.p;
return s < b.s;
}
};
int N, M, K, res, L[maxk];
int ns, trie[maxn * maxk][maxc], fail[maxn * maxk], flag[maxn * maxk], nxt1[maxn][maxc], nxt2[maxn][maxc];
char X[maxn], Y[maxn], S[maxk][maxn];
map<node, int> dp;
map<node, bool> inq;
void init(char *s, int nxt[maxn][maxc], int len)
{
for (int i = len - 1; i >= 0; --i)
{
memcpy(nxt[i], nxt[i + 1], sizeof(nxt[i]));
nxt[i][s[i] - 'A'] = i + 1;
}
}
void insert(char *s, int len, int id)
{
int p = 0;
for (int i = 0; i < len; ++i)
{
int c = s[i] - 'A';
if (!trie[p][c])
trie[p][c] = ns++;
p = trie[p][c];
}
flag[p] |= id;
}
void getFail()
{
queue<int> q;
for (int i = 0; i < maxc; ++i)
{
if (trie[0][i])
{
fail[trie[0][i]] = 0;
q.push(trie[0][i]);
}
}
while (!q.empty())
{
int p = q.front();
q.pop();
flag[p] |= flag[fail[p]];
for (int i = 0; i < maxc; ++i)
{
if (trie[p][i])
{
fail[trie[p][i]] = trie[fail[p]][i];
q.push(trie[p][i]);
}
else
trie[p][i] = trie[fail[p]][i];
}
}
}
void spfa()
{
queue<node> q;
node st = node{0, 0, 0, 0};
q.push(st);
inq[st] = 1, dp[st] = 0;
while (!q.empty())
{
node now = q.front();
q.pop();
inq[now] = 0;
int t = dp[now];
int x = now.x, y = now.y, p = now.p, s = now.s;
if (s == (1 << K) - 1)
res = max(res, t);
for (int i = 0; i < maxc; ++i)
{
int nx = nxt1[x][i], ny = nxt2[y][i], np = trie[p][i], ns = s | flag[np];
if (nx && ny)
{
node nxt = node{nx, ny, np, ns};
if (t + 1 > dp[nxt])
{
dp[nxt] = t + 1;
if (!inq[nxt])
{
q.push(nxt);
inq[nxt] = 1;
}
}
}
}
}
}
int main()
{
scanf("%d%d%d", &N, &M, &K);
for (int i = 0; i < K; ++i)
scanf("%d", L + i);
scanf("%s %s", X, Y);
init(X, nxt1, N);
init(Y, nxt2, M);
ns = 1;
for (int i = 0; i < K; i++)
{
scanf(" %s", S + i);
insert(S[i], L[i], 1 << i);
}
getFail();
spfa();
printf("%d\n", res);
return 0;
}