UVa 11855 Buzzwords

题目本质是要求统计频次,由于原始字符串长度不超过 1000 1000 1000,而枚举所有长度的子串时间复杂度为 O ( n 2 ) O(n^2) O(n2),因此可以考虑使用字符串散列予以解决。

如果您对字符串散列不熟悉,可以参考:字符串散列。

读入原始字符串,将所有空格去除,令此时的字符串长度为 n n n,接着从 1 1 1 到 n n n 枚举子串的长度,计数对应长度所有子串散列值的频次,按照要求输出即可,可以利用 STL \texttt{STL} STL( Standard Template Library \texttt{Standard Template Library} Standard Template Library)中的 map \texttt{map} map 容器类来统计频次。


参考代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int BASE = 16777213, MOD = 2147483647;
int main(int argc, char *argv[]) {
    cin.tie(0), cout.tie(0), ios::sync_with_stdio(false);
    string line;
    while (getline(cin, line)) {
        string s;
        for (auto c : line) if (c != ' ') s += c;
        int n = (int)s.length();
        long long h[1010], b[1010];
        h[0] = 0, b[0] = 1;
        for (int i = 1; i <= 1000; i++) b[i] = b[i - 1] * BASE % MOD;
        for (int i = 1; i <= n; i++) h[i] = (h[i - 1] * BASE + s[i - 1]) % MOD;
        bool empty = 0;
        for (int i = 1; i <= n; i++) {
            map<long long, int> mp;
            for (int j = 0; j + i - 1 < n; j++) {
                long long sh = (h[j + i] - h[j] * b[i] % MOD + MOD) % MOD;
                mp[sh]++;
            }
            int r = 0;
            for (auto p : mp) r = max(r, p.second);
            if (r > 1) { cout << r << '\n'; empty = 0; }
            else {
                if (!empty) cout << '\n';
                empty = 1;
            }
        }
    }
    return 0;
}
相关推荐
ZhengEnCi2 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
秋天的怀念_David2 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi3 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_6183 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang3 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
2601_970703834 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你02144 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
ZhengEnCi6 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Flynn Liang6 小时前
RAG 答非所问/幻觉怎么破?Spring AI QuestionAnswerAdvisor 召回优化实战(TopK/重排/混合检索)
人工智能·算法·spring·rag·幻觉·springai
liminla!6 小时前
SQL 从入门到进阶:语法速查与实战练习(完整优化版)
数据库·sql·算法