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;
}
相关推荐
z小猫不吃鱼5 分钟前
模型剪枝经典论文精读:DepGraph: Towards Any Structural Pruning
算法·机器学习·剪枝
Ulyanov1 小时前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头
牧以南歌〆1 小时前
数据结构<八>链式队列
c语言·数据结构·算法
Reart1 小时前
Leetcode 188.买卖股票的最佳时机4(718)
后端·算法
2601_950760791 小时前
BCMA:急性髓系白血病免疫治疗的新型可行靶点
人工智能·算法·蛋白
Reart2 小时前
Leetcode 123.买卖股票的最佳时期3(内有随心谈,718)
后端·算法
可编程芯片开发2 小时前
基于RMDCFT算法的天基雷达空间机动目标检测方法MATLAB仿真,对比FRFT和DFT算法
算法
noipp3 小时前
推荐题目:洛谷 B2099 矩阵交换行
线性代数·算法·矩阵
五条凪4 小时前
简单理解 BM25 与 TF-IDF
人工智能·算法·搜索引擎·全文检索·tf-idf
行者全栈架构师5 小时前
【码动四季】Spring Boot 可观测性体系:Micrometer + OpenTelemetry + Grafana 全链路搭建
java·算法·架构