bzoj 1559 AC自动机 + dp
思路:直接在状态图上跑dp,最后枚举一下42种一下的。。 这个枚举有点恶心。
#include<bits/stdc++.h> #define LL long long #define ll long long #define fi first #define se second #define mk make_pair #define PII pair<int, int> #define y1 skldjfskldjg #define y2 skldfjsklejg using namespace std; const int N = 100 + 7; const int M = 1e7 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1000000007; int n, m, up, top, id[N], bord[N][N]; string s[11], t[11]; bool vis[N]; bool cmp(const string &a, const string &b) { return a.size() > b.size(); } bool check(const string &a, const string &b) { for(int i = 0; i < a.size(); i++) { if(a.substr(i, b.size()) == b) return true; } return false; } int cal(const string &a, const string &b) { int l1 = a.size(), l2 = b.size(); for(int i = min(l1, l2) - 1; i >= 1; i--) { if(a.substr(l1 - i, i) == b.substr(0, i)) return i; } return 0; } struct Ac { int ch[N][26], val[N], f[N], tot, sz, depth[N]; LL dp[26][101][1 << 10]; Ac(int sz) {this->sz = sz;} void init() {tot = 0;}; int newNode() { tot++; f[tot] = 0; val[tot] = 0; memset(ch[tot], 0, sizeof(ch[tot])); return tot; } inline int idx(char c) {return c - 'a';} void addStr(string &s, int id) { int u = 0; for(int i = 0; i < s.size(); i++) { int c = idx(s[i]); if(!ch[u][c]) ch[u][c] = newNode(), depth[ch[u][c]] = depth[u] + 1; u = ch[u][c]; } val[u] |= 1 << id; } void build() { queue<int> que; for(int c = 0; c < sz; c++) { int v = ch[0][c]; if(!v) ch[0][c] = 0; else f[v] = 0, que.push(v); } while(!que.empty()) { int u = que.front(); que.pop(); val[u] |= val[f[u]]; for(int c = 0; c < sz; c++) { int v = ch[u][c]; if(!v) ch[u][c] = ch[f[u]][c]; else f[v] = ch[f[u]][c], que.push(v); } } } void solve() { dp[0][0][0] = 1; for(int k = 0; k < n; k++) { for(int u = 0; u <= tot; u++) { for(int c = 0; c < sz; c++) { int v = ch[u][c]; for(int s = 0; s <= up; s++) { dp[k + 1][v][s | val[v]] += dp[k][u][s]; } } } } LL ans = 0; for(int u = 0; u <= tot; u++) ans += dp[n][u][up]; cout << ans << '\n'; if(ans <= 42) { memset(vis, true, sizeof(vis)); sort(s, s + m, cmp); for(int i = 0; i < m; i++) for(int j = i + 1; j < m; j++) if(check(s[i], s[j])) vis[j] = false; for(int i = 0; i < m; i++) if(vis[i]) id[top] = top, t[top++] = s[i]; for(int i = 0; i < top; i++) for(int j = 0; j < top; j++) if(i != j) bord[i][j] = cal(t[i], t[j]); vector<string> vec; do { string ret = t[id[0]]; for(int i = 1; i < top; i++) { int len = bord[id[i - 1]][id[i]]; ret += t[id[i]].substr(len, 15); } if(ret.size() == n) vec.push_back(ret); } while(next_permutation(id, id + top)); sort(vec.begin(), vec.end()); for(int i = 0; i < vec.size(); i++) cout << vec[i] << '\n'; } } } ac(26); int main() { ac.init(); cin >> n >> m; for(int i = 0; i < m; i++) { cin >> s[i]; ac.addStr(s[i], i); } up = (1 << m) - 1; ac.build(); ac.solve(); return 0; } /* */