標籤:bzoj jsoi2007 trie圖 dp 字串
題目大意:給出一些字串。已知如果文章裡出現過這些字串中的一個,那麼就說這個文章是可讀的。問長度為l的文章有多少是可讀的文章。
思路:直接處理不太好弄, 我們可以統計出來不可讀的文章,然後用26^l減去就是可讀的文章總數。
將所有的字串建Trie圖,然後設f[i][j]為文章的第i個字元Trie圖中的第j個節點的時候不可讀的文章的數量。轉移就很簡單了。注意一下模數就行了。
CODE:
#include <queue>#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define MAX 10010#define MO 10007using namespace std;#define P(a) ((a) - 'A') struct Trie{ Trie *son[26],*fail; bool end,id;}mempool[MAX],*C = mempool,*root = C++; int cnt,length;char s[MAX];int f[110][MAX];//表示匹配到第i位trie圖中j時的種類數。顯然f[0][0] = 1; inline void Insert(char *s){ Trie *now = root; while(*s != '\0') { if(now->son[P(*s)] == NULL) now->son[P(*s)] = C++; now = now->son[P(*s)]; ++s; } now->end = true;} void BuildTrieGraph(){ static queue<Trie *> q; while(!q.empty()) q.pop(); for(int i = 0; i < 26; ++i) if(root->son[i] != NULL) root->son[i]->fail = root,q.push(root->son[i]); else root->son[i] = root; while(!q.empty()) { Trie *now = q.front(); q.pop(); for(int i = 0; i < 26; ++i) if(now->son[i] != NULL) { now->son[i]->fail = now->fail->son[i]; now->son[i]->end |= now->fail->son[i]->end; q.push(now->son[i]); } else now->son[i] = now->fail->son[i] ? now->fail->son[i]:root; }} int main(){ cin >> cnt >> length; for(int i = 1; i <= cnt; ++i) { scanf("%s",s); Insert(s); } BuildTrieGraph(); f[0][0] = 1; for(int i = 0; i < length; ++i) for(int j = 0; j < C - mempool; ++j) for(int k = 0; k < 26; ++k) { Trie *now = mempool[j].son[k]; if(!now->end) f[i + 1][now - mempool] = (f[i + 1][now - mempool] + f[i][j]) % MO; } int ans = 0; for(int i = 0; i < C - mempool; ++i) ans = (ans + f[length][i]) % MO; int total = 1; for(int i = 1; i <= length; ++i) total = total * 26 % MO; cout << (total - ans + MO) % MO << endl; return 0;}
BZOJ 1030 JSOI 2007 文本產生器 AC自動機+DP