洛谷P3346 [ZJOI2015]诸神眷顾的幻想乡(广义后缀自动机)
程序员文章站
2022-04-09 18:55:45
题意 "题目链接" Sol 广义SAM的板子题。 首先叶子节点不超过20,那么可以直接对每个叶子节点为根的子树插入到广义SAM中。 因为所有合法的答案一定是某个叶子节点为根的树上的一条链,因此这样可以统计出所有合法的答案 然后就是经典的本质不同子串问题了,$ans = \sum len[i] len ......
题意
sol
广义sam的板子题。
首先叶子节点不超过20,那么可以直接对每个叶子节点为根的子树插入到广义sam中。
因为所有合法的答案一定是某个叶子节点为根的树上的一条链,因此这样可以统计出所有合法的答案
然后就是经典的本质不同子串问题了,\(ans = \sum len[i] - len[fa[i]]\)
#include<bits/stdc++.h> #define ll long long using namespace std; const int maxn = 2e6 + 10; inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } int n, c, a[maxn], deg[maxn]; namespace sam { int fa[maxn], len[maxn], ch[maxn][11], tot = 1, root = 1, las = 1; int insert(int x, int pre) { int now = ++tot; len[now] = len[pre] + 1; for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now; if(!pre) {fa[now] = root; return now;} int q = ch[pre][x]; if(len[q] == len[pre] + 1) fa[now] = q; else { int nq = ++tot; fa[nq] = fa[q]; len[nq] = len[pre] + 1; memcpy(ch[nq], ch[q], sizeof(ch[q])); for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nq; fa[q] = fa[now] = nq; } return now; } ll calc() { ll ans = 0; for(int i = 1; i <= tot; i++) ans += len[i] - len[fa[i]]; return ans; } } vector<int> v[maxn], node; void dfs(int x, int _fa, int p) { p = sam::insert(a[x], p); for(auto &to : v[x]) { if(to == _fa) continue; dfs(to, x, p); } } int main() { n = read(); c = read(); for(int i = 1; i <= n; i++) a[i] = read(); for(int i = 1; i <= n - 1; i++) { int x = read(), y = read(); v[x].push_back(y); deg[x]++; v[y].push_back(x); deg[y]++; } for(int i = 1; i <= n; i++) if(deg[i] == 1) sam::las = 1, dfs(i, 0, 1); cout << sam::calc(); return 0; }
上一篇: 带你搭一个SpringBoot+SpringData JPA的环境
下一篇: 方法的重载