[HEOI2012]旅行问题

题目链接https://www.lydsy.com/JudgeOnline/problem.php?id=2746


题解

这个是讲课时候的题。

讲课的时候都在想怎么后缀自动机....

当然是能做啦,$SAM$这么强。

实际上是个$AC$自动机,按照题目模拟就行了。

代码

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 1 << 20 ;

const int mod = 1000000007 ;

const int P = 21 ;

queue <int> Q;

int n, m, ch[N][26], fail[N][25], dep[N], tail, cnt, pos[N << 1], lenth[N];

char str[N];

ll Hash[N];

void insert() {
int len = strlen(str);
int p = 0;
for (int i = 0; i < len; i ++ ) {
int c = str[i] - 'a';
if (!ch[p][c]) {
ch[p][c] = ++tail;
Hash[ch[p][c]] = (((Hash[p] * 26) % mod) + c) % mod;
}
pos[ ++ cnt] = ch[p][c];
p = ch[p][c];
}
} void getfail() {
dep[0] = 0;
for (int i = 0; i < 26; i ++ ) {
if (ch[0][i]) {
fail[ch[0][i]][0] = 0;
dep[ch[0][i]] = 1;
Q.push(ch[0][i]);
}
}
while (!Q.empty()) {
int top = Q.front();
Q.pop();
for (int i = 0; i < 26; i ++ ) {
if (!ch[top][i]) {
ch[top][i] = ch[fail[top][0]][i];
continue;
}
int u = ch[top][i];
fail[u][0] = ch[fail[top][0]][i];
dep[u] = dep[fail[u][0]] + 1;
for (int j = 1; j < P; j ++ ) {
fail[u][j] = fail[fail[u][j - 1]][j - 1];
}
Q.push(u);
}
}
} int getlca(int u, int v) {
if (dep[u] < dep[v]) {
swap(u, v);
}
int d = dep[u] - dep[v];
for (int i = 0; d; d >>= 1, i ++ ) {
if (d & 1) {
u = fail[u][i];
}
}
if (u == v) {
return u;
}
for (int p = P - 1; p >= 0; p -- ) {
if (fail[u][p] != fail[v][p]) {
u = fail[u][p];
v = fail[v][p];
}
}
return fail[u][0];
} int main() {
scanf("%d", &n);
memset(fail, 0, sizeof fail);
lenth[0] = 0;
for (int i = 1; i <= n; i ++ ) {
scanf("%s", str);
insert();
lenth[i] = strlen(str);
lenth[i] += lenth[i - 1];
}
getfail();
scanf("%d", &m);
while (m -- ) {
int p1, l1, p2, l2;
scanf("%d%d%d%d", &p1, &l1, &p2, &l2);
int t1 = pos[lenth[p1 - 1] + l1];
int t2 = pos[lenth[p2 - 1] + l2];
int lca = getlca(t1, t2);
printf("%lld\n", Hash[lca]);
}
return 0;
}

小结:注意一下AC自动机找LCA要倍增,别直接跳fail......

最新文章

  1. 使用Solr索引MySQL数据
  2. 在 JQuery Mobile 中实现瀑布流图库布局
  3. XP退役了,如何把Win7变成XP风格?| 怎么样去掉Win7的所有华丽效果? | 怎么样让Win7达到电脑最佳性能?
  4. iOS--更新cooped库
  5. &lt;context-param&gt;与&lt;init-param&gt;
  6. DataTable/Array Linq查询,groupby
  7. C#基础系列:实现自己的ORM(反射以及Attribute在ORM中的应用)
  8. Qt之进程间通信(IPC)
  9. cdoj 574 High-level ancients dfs序+线段树
  10. one problem about Apple Keychain in use
  11. Linux_jdk path (execute and install)
  12. easyui easyui-filebox 显示中文
  13. two sum II
  14. windows最简单的局部截图工具
  15. day44-Celery异步分布式
  16. sublime text3安装代码格式化的步骤
  17. A1022. Digital Library
  18. Java1.7 HashMap 实现原理和源码分析
  19. ACM题目————区间覆盖问题
  20. 170508、忘记jenkins密码或者修改jenkins密码

热门文章

  1. nginx大概工作机制
  2. triggerHandler(type, [data])
  3. [Luogu] 聪明的质监员
  4. 洛谷P4698 [CEOI2011]Hotel [贪心,二分,并查集]
  5. DP基础(线性DP)总结
  6. 【CUDA 基础】6.3 重叠内和执行和数据传输
  7. Linux下 Nginx 启动 重启 关闭
  8. 利用ceph-deploy部署ceph存储集群
  9. Ranorex连接Android
  10. IO之复制文件的四种方式