# 【AC自动机+矩阵快速幂】poj2778 DNA Sequence

1. 若ch[I][j] ==0 ,某个节点没有某一字符的儿子，考虑将其指向其失配节点的儿子：ch[I][j] = ch[f[I]][j];Tire数就变成Tire图了。

2.若val[f[I]]==1,某节点失配节点是危险节点，则将此节点标为危险节点。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 101;
const int mod = 100000;

int n, l;

struct Matrix{
ll mat[101][101];
int r, c;
Matrix(int x){ memset(mat, 0, sizeof(mat)); r = x; c = x; }

Matrix operator*(const Matrix &b) const{
Matrix res(b.r);
for (int i = 0; i <= b.r; i++){
for (int j = 0; j <= b.r; j++){
for (int k = 0; k <= b.r; k++){
res.mat[i][j] = (res.mat[i][j] + mat[i][k] * b.mat[k][j]) % mod;
}
}
}
return res;
}
};

Matrix Qpow(Matrix x, ll n){
Matrix res(x.c), tmp = x;
for (int i = 0; i <= x.c; i++) res.mat[i][i] = 1;

while (n){
if (n & 1) res = res *tmp;
n >>= 1;
tmp = tmp*tmp;
}

return res;
}

struct Trie{

int ch[maxn][26];
int val[maxn];
int last[maxn];
int f[maxn];
int sz;
int idx(char x){
if (x == 'A') return 0;
if (x == 'T') return 1;
if (x == 'C') return 2;
if (x == 'G') return 3;
}

void insert(char *s){
int u = 0, n = strlen(s);
for (int i = 0; i < n; i++){
int c = idx(s[i]);
if (!ch[u][c]){
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = 1;
}

void init(){
memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val));
sz = 1;
for (int i = 0; i < n; i++){
char str[55]; scanf("%s", str);
insert(str);
}
}

void build(){
queue<int> q;
memset(f, 0, sizeof(f));
memset(last, 0, sizeof(last));
for (int i = 0; i < 26; i++){
int u = ch[0][i];
if (u){ q.push(u); }
}
while (!q.empty()){
int r = q.front(); q.pop();
for (int i = 0; i < 26; i++){
int u = ch[r][i];
if (!u) {
ch[r][i] = ch[f[r]][i];
continue;
};
q.push(u);

int v = f[r];
while (v && !ch[v][i]) v = f[v];
f[u] = ch[v][i];
last[u] = val[f[u]] ? f[u] : last[f[u]];
if (val[f[u]] == 1) val[u] = 1;
}
}
}

Matrix getM(){
Matrix mp(sz);
for (int i = 0; i < sz; i++){
for (int j = 0; j < 4; j++){
if (!val[i] && !val[ch[i][j]])
mp.mat[i][ch[i][j]]++;
}
}
return mp;
}
};

Trie ac;
int main(){
while (~scanf("%d%d", &n, &l)){
ac.init();
ac.build();
Matrix m = ac.getM();
m = Qpow(m, l);
ll ans = 0;
for (int i = 0; i < ac.sz; i++){
ans = (ans + m.mat[0][i]) % mod;
}
cout << ans << endl;
}
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：【AC自动机+矩阵快速幂】poj2778 DNA Sequence 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)