【字符串哈希+二分】AcWing 3508. 最长公共子串
1.前后缀分解2.【前缀和+开区间二分】codeforces 1187 B. Letters Shop
3.【字符串哈希+二分】AcWing 3508. 最长公共子串
4.【二分+前缀和+后缀和】codeforces 2026 D. Sums of Segments5.【滑动窗口】codeforces 1290 A. Mind Control6.【三分】AcWing 3666. 士兵排阵7.【带权前缀和】codeforces 2044 H. Hard Demon Problem8.【区间合并+贡献法】codeforces 1789 C. Serval and Toxel's Arrays9.【离线+单调栈】AtCoder ABC379 F. Buildings 2题解
首先思考暴力枚举长度为
容易证明的是:若存在一个长度为
因此,不妨假设最长的公共子串的长度为
判断字符串
参考代码
#include<iostream> #include<vector> #include<unordered_set> #define IOS ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); using namespace std; using ull = unsigned long long; const int N = 10007; const int P = 131; ull p[N]; vector<vector<ull>> h1, h2; string s, t; int n, m; bool judge(char &ch) { return ch >= 'a' && ch <= 'z'; } void init() { n = s.size(), m = t.size(); p[0] = 1; for (int i = 1, j = max(n, m); i <= j; ++ i) p[i] = p[i - 1] * P; auto func = [&](string& str, vector<vector<ull>>& h, int &len) { for (int i = 0; i < len; ++ i) { if (judge(str[i])) { vector<ull> v = {0ULL}; int j = i; do { v.emplace_back(v.back() * P + str[i] - 'a'); ++ i; } while (i < len && judge(str[i])); h.emplace_back(v); } } }; func(s, h1, n), func(t, h2, m); } ull get(vector<ull>& vec, int l, int r) { return vec[r] - vec[l] * p[r - l]; } int main() { IOS cin >> s >> t; init(); auto check = [&](int x) -> bool { unordered_set<ull> ust; for (auto &h: h1) for (int i = x; i < h.size(); ++ i) ust.insert(get(h, i - x, i)); for (auto &h: h2) { for (int i = x; i < h.size(); ++ i) { ull val = get(h, i - x, i); if (ust.find(val) != ust.end()) return true; } } return false; }; int le = 0, ri = min(n, m), md; while (le < ri) { md = le + ri + 1 >> 1; if (check(md)) le = md; else ri = md - 1; } cout << le << '\n'; return 0; }
分类:
数据结构与算法
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee