Problem : 給若干個數字串,詢問這些串的全部本質不一樣的子串轉換成數字以後的和。
Solution : 首先將全部串丟進一個後綴自動機。因爲這道題詢問的是不一樣的子串之間的計數,不涉及子串的數目,所以考慮用後綴鏈即後綴自動機的nt轉移數組來作。首先將全部節點進行按照距離大小進行基數排序,而後從小到大枚舉每一個節點的出邊,假設當前點爲u,轉移到v,那麼更新的狀態爲cnt[v] += cnt[u], sum[v] += sum[u] + cnt[u] * ch,cnt[u]表示的是到達當前節點的子串的數量,sum[u]表示的是該節點所表示的串的答案。
須要注意的是具備前導0的串對答案沒有貢獻。node
#include <string> #include <iostream> using namespace std; const int N = 200008; const int mo = 2012; struct Suffix_Automaton { int nt[N][10], fail[N], a[N]; int last, root, tot; int p, q, np, nq; int c[N], rk[N], cnt[N], sum[N]; int newnode(int len) { for (int i = 0; i < 10; ++i) nt[tot][i] = -1; fail[tot] = -1; a[tot] = len; c[tot] = rk[tot] = cnt[tot] = sum[tot] = 0; return tot++; } void clear() { tot = 0; last = root = newnode(0); } void insert(int ch) { p = last; last = np = newnode(a[p] + 1); for (; ~p && nt[p][ch] == -1; p = fail[p]) nt[p][ch] = np; if (p == -1) fail[np] = root; else { q = nt[p][ch]; if (a[p] + 1 == a[q]) fail[np] = q; else { nq = newnode(a[p] + 1); for (int i = 0; i < 10; ++i) nt[nq][i] = nt[q][i]; fail[nq] = fail[q]; fail[q] = fail[np] = nq; for (; ~p && nt[p][ch] == q; p = fail[p]) nt[p][ch] = nq; } } } void solve() { for (int i = 0; i < tot; ++i) c[a[i]]++; for (int i = 1; i < tot; ++i) c[i] += c[i - 1]; for (int i = 0; i < tot; ++i) rk[--c[a[i]]] = i; cnt[root] = 1; for (int i = 0; i < tot; ++i) { int u = rk[i]; for (int j = 0; j < 10; ++j) if (~nt[u][j]) { if (i == 0 && j == 0) continue; int v = nt[u][j]; cnt[v] += cnt[u ]; sum[v] += sum[u] * 10 + j * cnt[u]; sum[v] %= mo; } } int ans = 0; for (int i = 0; i < tot; ++i) { ans += sum[i]; ans %= mo; } cout << ans << endl; } }sam; int main() { cin.sync_with_stdio(0); int n; while (cin >> n) { string s; sam.clear(); for (int i = 1; i <= n; ++i) { cin >> s; sam.last = 0; for (int j = 0, len = s.length(); j < len; ++j) sam.insert(s[j] - '0'); } sam.solve(); } }