版本比较
学习笔记:KMP & ACAM
正文
增加 76 行删除 1 行
728 行未改动全部展开729730731732733733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813728 行未改动全部展开}```::::
## 2.3.4 其它练习题## 2.3.4 [Video Game G](https://www.luogu.com.cn/problem/P3041)
这道题涉及字符串的匹配,虽然并不是一个标准的多模匹配问题,但是我们还是考虑 ACAM。建立出 ACAM 之后,我们考虑要求的这个字符串本质是什么。
首先定义一个节点的点权为走到这个节点之后可以通过跳失配指针到达的点表示的字符串结尾数之和,这一个先让可以在求失配指针的时候顺带推出。那么问题可以转化为:给你一个有向图,只能沿着边移动,求一条长度为 $k$ 的路径使得经过的点点权之和最大。
这是一个简单的图上 DP。首先设 $dp_{i,u}$ 表示走 $i$ 步之后来到 $u$ 号节点产生的最大点权和。初始化数组为 $-\infin$,设 $dp_{0,0}=0$,直接枚举每一条边转移即可。我代码具体实现的时候使用了滚动数组滚掉了 $i$ 这一维。
::::success[code]```cpp line-numbers#include <bits/stdc++.h>#define endl '\n'using namespace std;
const int N = 3e2 + 5;int n, k, cnt = 0, dp[2][N];vector<pair<int, int> > w;queue<int> q;struct Node { int ch[3], fail, cnt; } t[N];string s;
void insert(string s) { int u = 0; for(int i = 0; i < s.size(); i ++ ) { int k = s[i] - 'A'; if(!t[u].ch[k]) t[u].ch[k] = ++ cnt; u = t[u].ch[k]; } t[u].cnt ++ ;}
void get_fail() { for(int i = 0; i < 3; i ++ ) if(t[0].ch[i]) q.push(t[0].ch[i]); while(!q.empty()) { int u = q.front(); q.pop(); for(int i = 0; i < 3; i ++ ) { int v = t[u].ch[i]; if(v) { t[v].fail = t[t[u].fail].ch[i]; t[v].cnt += t[t[v].fail].cnt; q.push(v); } else t[u].ch[i] = t[t[u].fail].ch[i]; } } for(int i = 0; i <= cnt; i ++ ) for(int j = 0; j < 3; j ++ ) w.push_back(make_pair(i, t[i].ch[j]));}
int main() { ios :: sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> n >> k; for(int i = 1; i <= n; i ++ ) cin >> s, insert(s); get_fail(); memset(dp[0], -0x3f, sizeof dp[0]); dp[0][0] = 0; for(int i = 1; i <= k; i ++ ) { memset(dp[1], -0x3f, sizeof dp[1]); for(auto [u, v] : w) dp[1][v] = max(dp[1][v], dp[0][u] + t[v].cnt); swap(dp[0], dp[1]); } int ans = 0; for(int i = 0; i <= cnt; i ++ ) ans = max(ans, dp[0][i]); cout << ans << endl; return 0;} ::::
## 2.3.5 其它练习题
难度按照个人主观升序排序。
- [单词](https://www.luogu.com.cn/problem/P3966)- [Sensoring G](https://www.luogu.com.cn/problem/P3121)- [通配符匹配](https://www.luogu.com.cn/problem/P3167)- [病毒](https://www.luogu.com.cn/problem/P2444)- [数数](https://www.luogu.com.cn/problem/P3311)- [Critical Misread](https://www.luogu.com.cn/problem/AT_abc458_f)- [Divljak](https://www.luogu.com.cn/problem/P5840)