经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
BZOJ3238: [Ahoi2013]差异(后缀自动机)
来源:cnblogs  作者:自为风月马前卒  时间:2018/12/17 9:47:49  对本文有异议

题意

题目链接

Sol

前面的可以直接算

然后原串翻转过来,这时候变成了求任意两个前缀的最长公共后缀,显然这个值应该是\(len[lca]\),求出\(siz\)乱搞一下

  1. #include<bits/stdc++.h>
  2. #define int long long
  3. #define LL long long
  4. using namespace std;
  5. const int MAXN = 1e6 + 10;
  6. LL N;
  7. char a[MAXN];
  8. int fa[MAXN], len[MAXN], siz[MAXN], ch[MAXN][26], tot = 1, las = 1, root = 1, sum[MAXN];
  9. LL ans;
  10. vector<int> v[MAXN];
  11. void insert(int x) {
  12. int now = ++tot, pre = las; las = now; len[now] = len[pre] + 1;
  13. for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now;
  14. if(!pre) fa[now] = root;
  15. else {
  16. int q = ch[pre][x];
  17. if(len[pre] + 1 == len[q]) fa[now] = q;
  18. else {
  19. int ns = ++tot; fa[ns] = fa[q]; len[ns] = len[pre] + 1;
  20. memcpy(ch[ns], ch[q], sizeof(ch[q]));
  21. fa[q] = fa[now] = ns;
  22. for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = ns;
  23. }
  24. }
  25. siz[now] = 1;
  26. }
  27. void Build() {
  28. for(int i = 2; i <= tot; i++) v[fa[i]].push_back(i);
  29. }
  30. LL res = 0;
  31. void dp(int x) {
  32. for(int i = 0; i < v[x].size(); i++) {
  33. int to = v[x][i];
  34. dp(to);
  35. res += 1ll * len[x] * siz[x] * siz[to];
  36. siz[x] += siz[to];
  37. }
  38. }
  39. signed main() {
  40. //freopen("a.in", "r", stdin);
  41. scanf("%s", a + 1);
  42. N = strlen(a + 1);
  43. reverse(a + 1, a + N + 1);
  44. for(int i = 1; i <= N; i++) insert(a[i] - 'a');
  45. Build(); dp(root);
  46. for(int i = 1; i <= N; i++) ans += (LL) (1ll * i * (N - i) + 1ll * (N * (N + 1) / 2 - (i * (i + 1) / 2)));
  47. cout << ans - res * 2;
  48. return 0;
  49. }
  50. /*
  51. abbabbabbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  52. */
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号