K - Count the string kmp_Next数组应用

探讨了AekdyCoin在字符串问题上的专长,特别是对于字符串前缀匹配次数的计算方法。通过实例“abab”,展示了如何利用KMP算法预处理得到Next数组,进而计算所有前缀在字符串中的总匹配次数。
It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example: 
s: "abab" 
The prefixes are: "a", "ab", "aba", "abab" 
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6. 
The answer may be very large, so output the answer mod 10007. 

InputThe first line is a single integer T, indicating the number of test cases. 
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters. 
OutputFor each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.Sample Input

1
4
abab

Sample Output

6

一个结论:cnt[i] 表示 因为加入i字符而增加的 以i字符结束的前缀数目
cnt[i] = cnt[Next[i]] + 1
Next[]数组表示前j个字符中最长的相同前缀后缀长度
证明:
如果Next[i]==0 也就是说 i字符没有在之前出现过,那么因为加入字符i增加的前缀只有0-i这个字符串
否则 增加的数目要考虑由于第i-k个字符到第i个字符组成的字符串是前缀的情况,增加的数目为这种前缀的数目+1,那么这种前缀的数目如何求?
显然,考虑i之前最长匹配的前缀后缀,在最长匹配处加入字符i增加的前缀 等于 在i处加入字符i增加的前缀

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include <sstream>
#include<string>
#include<cstring>
#include<list>
using namespace std;
#define MAXN 200002
#define INF 0x3f3f3f3f
#define M 10007
typedef long long LL;
/*
输出字符串中所有前缀在字符串中出现的次数
ababab
*/
char t[MAXN];
int Next[MAXN],cnt[MAXN];
void kmp_pre(char t[])
{
    int m = strlen(t);
    int j,k;
    j = 0;k = Next[0] = -1;
    while(j<m)
    {
        if(k==-1||t[j]==t[k])
            Next[++j] = ++k;
        else
            k = Next[k];
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int l,ans=0;
        scanf("%d",&l);
        scanf("%s",t);
        kmp_pre(t);
        for(int i=1;i<=l;i++)
        {
            cnt[i] = (cnt[Next[i]]+1);
            ans = (ans+cnt[i])%M;
        }
        printf("%d\n",ans);
    }
}

 

转载于:https://www.cnblogs.com/joeylee97/p/6681223.html

#include <iostream> #include <vector> #include <string> #include <random> #include <chrono> #include <iomanip> using namespace std; using namespace std::chrono; // KMP算法:构建next数组 vector<int> buildNext(const string& pattern) { int n = pattern.length(); vector<int> next(n, 0); int j = 0; for (int i = 1; i < n; ++i) { while (j > 0 && pattern[i] != pattern[j]) { j = next[j - 1]; } if (pattern[i] == pattern[j]) { ++j; } next[i] = j; } return next; } // KMP算法:搜索并返回匹配位置和比较次数 pair<vector<int>, long long> kmpSearch(const string& text, const string& pattern) { vector<int> next = buildNext(pattern); vector<int> matches; int m = pattern.length(); int n = text.length(); int i = 0, j = 0; long long comparisons = 0; while (i < n) { comparisons++; if (text[i] == pattern[j]) { ++i; ++j; if (j == m) { matches.push_back(i - m); j = next[j - 1]; } } else { if (j > 0) j = next[j - 1]; else ++i; } } return {matches, comparisons}; } // BM算法:构建坏字符规则表 vector<int> buildBadChar(const string& pattern) { vector<int> badChar(256, -1); for (int i = 0; i < pattern.size(); ++i) { badChar[(unsigned char)pattern[i]] = i; } return badChar; } // BM算法:搜索并返回匹配位置和比较次数 pair<vector<int>, long long> bmSearch(const string& text, const string& pattern) { vector<int> badChar = buildBadChar(pattern); int m = pattern.length(); int n = text.length(); vector<int> matches; long long comparisons = 0; int s = 0; while (s <= n - m) { int j = m - 1; while (j >= 0) { comparisons++; if (text[s + j] != pattern[j]) break; --j; } if (j < 0) { matches.push_back(s); s += (s + m < n) ? m - badChar[text[s + m]] : 1; } else { s += max(1, j - badChar[text[s + j]]); } } return {matches, comparisons}; } // 随机生成指定字符集的字符串 string generateRandomString(int length, const string& charset) { static random_device rd; static mt19937 gen(rd()); uniform_int_distribution<> dis(0, charset.size() - 1); string result; for (int i = 0; i < length; ++i) { result += charset[dis(gen)]; } return result; } // 插入模式串到主串的指定位置(前、中、后) void insertPattern(string& text, const string& pattern, const string& position) { int idx; if (position == "front") idx = 0; else if (position == "middle") idx = (text.size() - pattern.size()) / 2; else if (position == "back") idx = text.size() - pattern.size(); else return; text.replace(idx, pattern.size(), pattern); } int main() { // 字符集定义 string charset_bin = "01"; string charset_10 = "0123456789"; string charset_ascii = ""; for (char c = 32; c <= 126; ++c) charset_ascii += c; // 主串长度 const int TEXT_LEN = 100000; // 模式串长度 vector<int> patternLengths = {5, 15, 30}; // 场景参数 vector<string> charsets = {"01", "0123456789", "ascii"}; vector<string> positions = {"front", "middle", "back"}; cout << left << setw(8) << "Charset" << setw(8) << "P_Len" << setw(10) << "Pos" << setw(10) << "Alg" << setw(15) << "Time(us)" << setw(15) << "Compares" << endl; cout << string(60, '-') << endl; for (auto& cs_label : charsets) { string charset = (cs_label == "01") ? charset_bin : (cs_label == "0123456789") ? charset_10 : charset_ascii; string text = generateRandomString(TEXT_LEN, charset); for (int plen : patternLengths) { for (auto& pos : positions) { string pattern = generateRandomString(plen, charset); string text_copy = text; insertPattern(text_copy, pattern, pos); // KMP测试 auto start = high_resolution_clock::now(); auto [kmp_matches, kmp_compares] = kmpSearch(text_copy, pattern); auto end = high_resolution_clock::now(); auto kmp_time = duration_cast<microseconds>(end - start).count(); // BM测试 start = high_resolution_clock::now(); auto [bm_matches, bm_compares] = bmSearch(text_copy, pattern); end = high_resolution_clock::now(); auto bm_time = duration_cast<microseconds>(end - start).count(); cout << setw(8) << cs_label << setw(8) << plen << setw(10) << pos << setw(10) << "KMP" << setw(15) << kmp_time << setw(15) << kmp_compares << endl; cout << setw(8) << cs_label << setw(8) << plen << setw(10) << pos << setw(10) << "BM" << setw(15) << bm_time << setw(15) << bm_compares << endl; } } } return 0; }
11-10
内容概要:本文详细介绍了一个基于C++的养老院管理系统的设计与实现,旨在应对人口老龄化带来的管理挑战。系统通过整合住户档案、健康监测、护理计划、任务调度等核心功能,构建了从数据采集、清洗、AI风险预测到服务调度与可视化的完整技术架构。采用C++高性能服务端结合消息队列、规则引擎和机器学习模型,实现了健康状态实时监控、智能任务分配、异常告警推送等功能,并解决了多源数据整合、权限安全、老旧硬件兼容等实际问题。系统支持模块化扩展与流程自定义,提升了养老服务效率、医护协同水平和住户安全保障,同时为运营决策提供数据支持。文中还提供了关键模块的代码示例,如健康指数算法、任务调度器和日志记录组件。; 适合人群:具备C++编程基础,从事软件开发或系统设计工作1-3年的研发人员,尤其是关注智慧养老、医疗信息系统开发的技术人员。; 使用场景及目标:①学习如何在真实项目中应用C++构建高性能、可扩展的管理系统;②掌握多源数据整合、实时健康监控、任务调度与权限控制等复杂业务的技术实现方案;③了解AI模型在养老场景中的落地方式及系统架构设计思路。; 阅读建议:此资源不仅包含系统架构与模型描述,还附有核心代码片段,建议结合整体设计逻辑深入理解各模块之间的协同机制,并可通过重构或扩展代码来加深对系统工程实践的掌握。
内容概要:本文详细介绍了一个基于C++的城市交通流量数据可视化分析系统的设计与实现。系统涵盖数据采集与预处理、存储与管理、分析建模、可视化展示、系统集成扩展以及数据安全与隐私保护六大核心模块。通过多源异构数据融合、高效存储检索、实时处理分析、高交互性可视化界面及模块化架构设计,实现了对城市交通流量的实时监控、历史趋势分析与智能决策支持。文中还提供了关键模块的C++代码示例,如数据采集、清洗、CSV读写、流量统计、异常检测及基于SFML的柱状图绘制,增强了系统的可实现性与实用性。; 适合人群:具备C++编程基础,熟悉数据结构与算法,有一定项目开发经验的高校学生、研究人员及从事智能交通系统开发的工程师;适合对大数据处理、可视化技术和智慧城市应用感兴趣的技术人员。; 使用场景及目标:①应用于城市交通管理部门,实现交通流量实时监测与拥堵预警;②为市民出行提供路径优化建议;③支持交通政策制定与信号灯配时优化;④作为智慧城市建设中的智能交通子系统,实现与其他城市系统的数据协同。; 阅读建议:建议结合文中代码示例搭建开发环境进行实践,重点关注多线程数据采集、异常检测算法与可视化实现细节;可进一步扩展机器学习模型用于流量预测,并集成真实交通数据源进行系统验证。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值