【LG4070】[SDOI2016]生成魔咒

题面

洛谷

题解

如果我们不用在线输的话,那么答案就是对于所有状态\(i\)

\[\sum (i.len-i.fa.len)
\]

现在我们需要在线询问,那么因为\(SAM\)是在线算法,我们考虑每次的对答案的贡献。

那么产生的贡献就是\(last.len-last.fa.len\)。

与\(yyb\)的对话:

Q:为什么构建自动机时中间过程新加的点不会算到最后答案中呢?

A:不影响答案啊,你在两个len之间断开,对于答案的贡献不变。

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <tr1/unordered_map>
using namespace std;
using namespace std::tr1;
inline int gi() {
register int data = 0, w = 1;
register char ch = 0;
while (!isdigit(ch) && ch != '-') ch = getchar();
if (ch == '-') w = -1, ch = getchar();
while (isdigit(ch)) data = 10 * data + ch - '0', ch = getchar();
return w * data;
}
const int MAX_N = 1e5 + 5;
struct Node {
unordered_map<int, int> ch;
int len, fa;
} t[MAX_N << 1];
int tot = 1, lst = 1;
long long ans = 0;
void extend(int c) {
int New = ++tot;
t[lst].ch[c] = New;
t[New].len = t[lst].len + 1;
int p = t[lst].fa; lst = tot;
while (p && t[p].ch.find(c) == t[p].ch.end()) t[p].ch[c] = New, p = t[p].fa;
if (!p) t[New].fa = 1;
else {
int q = t[p].ch[c];
if (t[q].len == t[p].len + 1) t[New].fa = q;
else {
int _q = ++tot; t[_q] = t[q];
t[New].fa = t[q].fa = _q, t[_q].len = t[p].len + 1;
while (p) {
unordered_map<int, int> :: iterator ite;
ite = t[p].ch.find(c);
if (ite == t[p].ch.end() || ite->second != q) break;
t[p].ch[c] = _q;
p = t[p].fa;
}
}
}
ans += t[New].len - t[t[New].fa].len;
} int main () {
#ifndef ONLINE_JUDGE
freopen("cpp.in", "r", stdin);
#endif
int N = gi();
for (int i = 1; i <= N; i++) extend(gi()), printf("%lld\n", ans);
return 0;
}

最新文章

  1. AE+C# 版本更新问题 命名空间“ESRI”中不存在类型或命名空间名称“Arcgis”(是缺少程序集引用吗?)
  2. spark转换集合为RDD
  3. 1、JS的数据类型
  4. 借助 MySQLTuner 优化 MySQL 性能(转载的一篇文章)
  5. spring整合quartz并持久化
  6. 深入Java集合学习系列:HashMap的实现原理--转
  7. delphi实现ado的高级功能
  8. Qt读写二进制文件
  9. 【转】CentOS上安装 jdk:rpm安装和源码安装
  10. ASP.NET Web Api构建基于REST风格的服务实战系列教程
  11. 卸载jdk以及重新安装jdk
  12. 【2017-03-10】Tsql语句基础、条件,高级查询
  13. TypeScript入门-基本数据类型
  14. PID控制算法研究
  15. WinServer配置MySQL主从同步
  16. locust压测rpc协议
  17. oracle 12514文件解决
  18. CentOS 7 使用 ACL 设置文件权限
  19. 学习笔记2—MATLAB的copyfile技巧
  20. MVC part4

热门文章

  1. Vue入门(二)之数据绑定
  2. Win10家庭版、专业版、企业版、教育版各版本功能区别对照表
  3. 建站相关-github+hexo, Markdown
  4. CSS| position定位和float浮动
  5. MySQl新特性 GTID
  6. Windows DHCP备份还原命令
  7. from urllib.request import urlopen
  8. VS2017C++单元测试
  9. facebook api &amp; oauth protocal
  10. [python] 在 python2和3中关于类继承的 super方法简要说明