版本比较
P2414 [NOI2011] 阿狸的打字机
正文
增加 11 行删除 11 行
33 行未改动3435363738383940414217 行未改动6061626364646566676869707172727374757627 行未改动10410510610710810810911011111211 行未改动1241251261271281281291301311324 行未改动13713813914014114114214314414576 行未改动22222322422522622622722822923083 行未改动31431531631731831831932032132254 行未改动37737837938038138138238338438555 行未改动441442443444445445446447448449132 行未改动全部展开58258358458558658658733 行未改动 cin >> m; for(int i = 0; i < m; i++){ int x, y; cin >> x >> y; x--; x--; y--; string p = strs[x], t = strs[y]; int cnt = 0; int n = t.size();17 行未改动 return 0;}```
时间复杂度 $O(m \cdot |s|^2)$。 时间复杂度 $O(m \cdot |s|^2)$。
ps:$|s|$ 输入字符串 $S$ 的长度,$n$ 打印串的数量,$m$ 如题意。
理论 $20pts$,实际跑了 $70pts$?(数据过水?)。[record](https://www.luogu.com.cn/record/249195257)
#### 2.KMP
先模拟打字机生成所有打印串,再对每个查询用 KMP 算法做模式匹配。 先模拟打字机生成所有打印串,再对每个查询用 KMP 算法做模式匹配。$next$ 记录模式串的自匹配信息,以便在匹配失败时能够跳过不必要的比较。
简述 **KMP**:- 当字符匹配时,同时移动文本串和模式串指针。27 行未改动 } } return ans;}vector<string> strs; vector<string> strs;string now;int main(){ ios::sync_with_stdio(false); cin.tie(nullptr);11 行未改动 cin >> m; while (m--){ int x, y; cin >> x >> y; x--; x--; y--; string p = strs[x]; string t = strs[y]; vector<int> next = pre(p);4 行未改动}```
时间复杂度 $O(m \cdot|s|)$。 时间复杂度 $O(m \cdot|s|)$。不开 `O2` $50pts$,开了依旧 $70pts$。[record](https://www.luogu.com.cn/record/249218457)
### 二、优化嗯,挺快的,有点玄学。76 行未改动 cin >> m; for(int i = 0; i < m; i++){ int x, y; cin >> x >> y; x--; x--; y--; if(strs[x].size() > strs[y].size()){ cout << 0 << '\n'; continue;83 行未改动 cin >> m; while(m--){ int x, y; cin >> x >> y; x--; x--; y--; cout << query(strs[y], x) << '\n'; } return 0;54 行未改动 for(int i = 0; i < 26; i++){ if(son[0][i]) q.push(son[0][i]); } while(!q.empty()){ int u = q.front(); int u = q.front(); q.pop(); for(int i = 0; i < 26; i++){ int v = son[u][i]; if(v){55 行未改动```**【核心思想】**按y值分组处理查询,避免重复计算。1. 构建Trie树时记录每个打印串的结束位置。2. 对查询按y排序,相同y的查询一起处理 。 2. 对查询按y排序,相同y的查询一起处理 。3. 对每个y,从对应Trie节点向上回溯到根节点。4. 在回溯过程中统计所有经过节点对应的打印串出现次数。5. 使用时间戳标记避免重复清空数组。
132 行未改动全部展开4. 遇到字符:在树状数组中标记当前节点 DFS 序位置。5. 遇到退格:取消上一个节点的标记。6. 遇到打印:处理对应 y 的所有查询。7. 查询时通过树状数组区间求和统计出现次数。
时间复杂度:$O(|s| + m) \log |s|)$,达到理论最优。[record](https://www.luogu.com.cn/record/250421595)