KMP,ACM集训

news2024/11/25 20:23:44

目录

                                831. KMP字符串

输入格式

输出格式

数据范围

输入样例:

输出样例:

 解析:KMP模板

                        D - Cyclic Nacklace

解析:KMP-next数组应用+循环字符串判断

                                F - Power Strings

解析:KMP-next数组应用+循环字符串判断

                                H - Count the string

 解析:next数组理解

                                J - String Problem

 解析:kmp求循环节,最小/最大表示法


                                831. KMP字符串

831. KMP字符串 - AcWing题库

给定一个字符串 S,以及一个模式串 P,所有字符串中只包含大小写英文字母以及阿拉伯数字。

模式串 P 在字符串 S 中多次作为子串出现。

求出模式串 P 在字符串 S 中所有出现的位置的起始下标。

输入格式

第一行输入整数 N,表示字符串 P 的长度。

第二行输入字符串 P。

第三行输入整数 M,表示字符串 S 的长度。

第四行输入字符串 S。

输出格式

共一行,输出所有出现位置的起始下标(下标从 00 开始计数),整数之间用空格隔开。

数据范围

1≤N≤105
1≤M≤106

输入样例:
3
aba
5
ababa
输出样例:
0 2

 解析:KMP模板

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 1e5 + 5, M = 1e6 + 5;

int n, m;
string s, p;
int ne[N];

int main() {
	cin >> n >> p >> m >> s;
	p.insert(0," ");
	s.insert(0," ");
	for (int i = 2, j = 0; i <= n; i++) {
		while (j && p[i] != p[j + 1])j = ne[j];
		if (p[i] == p[j + 1])j++;
		ne[i] = j;
	}
	for (int i = 1, j = 0; i <= m; i++) {
		while (j && s[i] != p[j + 1])j = ne[j];
		if (s[i] == p[j + 1])j++;
		if (j == n) {
			printf("%d ", i - n);
			j = ne[j];
		}
	}
	return 0;
}

                        D - Cyclic Nacklace

https://vjudge.net/contest/582298#problem/D

CC always becomes very depressed at the end of this month, he has checked his credit card yesterday, without any surprise, there are only 99.9 yuan left. he is too distressed and thinking about how to tide over the last days. Being inspired by the entrepreneurial spirit of "HDU CakeMan", he wants to sell some little things to make money. Of course, this is not an easy task.

As Christmas is around the corner, Boys are busy in choosing christmas presents to send to their girlfriends. It is believed that chain bracelet is a good choice. However, Things are not always so simple, as is known to everyone, girl's fond of the colorful decoration to make bracelet appears vivid and lively, meanwhile they want to display their mature side as college students. after CC understands the girls demands, he intends to sell the chain bracelet called CharmBracelet. The CharmBracelet is made up with colorful pearls to show girls' lively, and the most important thing is that it must be connected by a cyclic chain which means the color of pearls are cyclic connected from the left to right. And the cyclic count must be more than one. If you connect the leftmost pearl and the rightmost pearl of such chain, you can make a CharmBracelet. Just like the pictrue below, this CharmBracelet's cycle is 9 and its cyclic count is 2:


Now CC has brought in some ordinary bracelet chains, he wants to buy minimum number of pearls to make CharmBracelets so that he can save more money. but when remaking the bracelet, he can only add color pearls to the left end and right end of the chain, that is to say, adding to the middle is forbidden.
CC is satisfied with his ideas and ask you for help.

Input

The first line of the input is a single integer T ( 0 < T <= 100 ) which means the number of test cases.
Each test case contains only one line describe the original ordinary chain to be remade. Each character in the string stands for one pearl and there are 26 kinds of pearls being described by 'a' ~'z' characters. The length of the string Len: ( 3 <= Len <= 100000 ).

Output

For each case, you are required to output the minimum count of pearls added to make a CharmBracelet.

Sample

InputcopyOutputcopy
3
aaa
abca
abcde
0
2
5

解析:KMP-next数组应用+循环字符串判断

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 1e5 + 100, M = 1e4 + 5;
char str[N];
int ne[N];

int main() {
	int T;
	scanf("%d", &T);
	while (T--) {
		//memset(str, 0, sizeof(str));//千万不要加这句,加了就会WA,我也不知道为什么
		scanf("%s", str + 1);
		int len = strlen(str + 1);
		int n = len;
		for (int i = 2, j = 0; i <= n; i++) {
			while (j && str[i] != str[j + 1])j = ne[j];
			if (str[i] == str[j + 1])j++;
			ne[i] = j;
		}
		int r = len-ne[len];
		if (ne[len] == 0) {
			printf("%d\n", len);
		}
		else {
			if (len % r == 0)
				printf("0\n");
			else
				printf("%d\n", r - len % r);
		}
	}
	return 0;
}

                                F - Power Strings

Nefu字符串 - Virtual Judge (vjudge.net)

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).

Input

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.

Output

For each s you should print the largest n such that s = a^n for some string a.

Sample

InputcopyOutputcopy
abcd
aaaa
ababab
.
1
4
3

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

Sponsor

解析:KMP-next数组应用+循环字符串判断

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 1e7 + 5;
int ne[N];
char str[N];

int main() {
	while (scanf("%s",  str + 1) != EOF) {
		if (str[1] == '.')
			break;
		int n = strlen(str + 1);
		for (int i = 2, j = 0; i <= n; i++) {
			while (j && str[i] != str[j + 1])j = ne[j];
			if (str[i] == str[j + 1])j++;
			ne[i] = j;
		}
		int r = n - ne[n];
		if (n % r == 0)
			printf("%d\n", n / r);
		else {
			printf("1\n");
		}
	}
	return 0;
}

                                H - Count the string

 Nefu字符串 - Virtual Judge (vjudge.net)

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.

Input

The 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.

Output

For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.

Sample

InputcopyOutputcopy
1
4
abab
6

 解析:next数组理解

KMP中next数组的含义:0 - i 中的最大前缀后缀匹配

预处理出next数组,可知每个next数组记录该串的最大前缀的长度(数值上等价于下标)。那么对于某一个长位n的子串s,除了 它本身和模板串匹配外,还有它的最大相同后缀。
那么, ans = 本身的一个 + 最大相同后缀
关于不重不漏,由于答案的第一部分的头部都是模板串的第一个字符,对不同长度一定不同,对第二部分,末尾字符不会相同,同样不会重复

 虽然next数组统计的时最大前后缀,但大的后缀有前缀,那么大后缀中的小后缀一定也有前缀

注意:这道题中相同的部分不应该重叠,如:aaa 的答案为5

所以当前后缀相交时,此部分不计入答案。

好好理解理解!!!!

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 2e5 + 5, P = 131,mod= 10007;
int n;
char str[N];
int ne[N];

int main() {
	int T;
	scanf("%d", &T);
	while (T--) {

		scanf("%d%s",&n, str + 1);
		for (int i = 2, j = 0; i <= n; i++) {
			while (j && str[i] != str[j + 1])j = ne[j];
			if (str[i] == str[j+1])j++;
			ne[i] = j;
		}
		LL ans = 0;
		for (int i = 1; i <= n; i++) {
			if (ne[i] != 0)
				ans=(ans+1)%mod;
		}
		ans = (ans + n) % mod;
		printf("%lld\n", ans);
	}
	return 0;
}

                                J - String Problem

Nefu字符串 - Virtual Judge (vjudge.net)

Give you a string with length N, you can generate N strings by left shifts. For example let consider the string “SKYLONG”, we can generate seven strings:
String Rank
SKYLONG 1
KYLONGS 2
YLONGSK 3
LONGSKY 4
ONGSKYL 5
NGSKYLO 6
GSKYLON 7
and lexicographically first of them is GSKYLON, lexicographically last is YLONGSK, both of them appear only once.
  Your task is easy, calculate the lexicographically fisrt string’s Rank (if there are multiple answers, choose the smallest one), its times, lexicographically last string’s Rank (if there are multiple answers, choose the smallest one), and its times also.

Input

  Each line contains one line the string S with length N (N <= 1000000) formed by lower case letters.

Output

Output four integers separated by one space, lexicographically fisrt string’s Rank (if there are multiple answers, choose the smallest one), the string’s times in the N generated strings, lexicographically last string’s Rank (if there are multiple answers, choose the smallest one), and its times also.

Sample

InputcopyOutputcopy
abcder
aaaaaa
ababab
1 1 6 1
1 6 1 6
1 3 2 3

 解析:kmp求循环节,最小/最大表示法

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 1e6 + 5;

string str;
int ne[N];
int minrepresentation(string s) {
	int len = s.length();
	s = " " + s + s;
	int i = 1, j = 2;
	while (j <= len) {
		int k = 0;
		while (k < len && s[i + k] == s[j + k])k++;
		if (s[i + k] > s[j + k])i += k + 1;
		else j += k + 1;
		if (i == j)j++;
		if (i > j)swap(i, j);
	}
	return i;
}
int maxrepresentation(string s) {
	int len = s.length();
	s = " " + s + s;

	int i = 1, j = 2;
	while (j <= len) {
		int k = 0;
		while (k < len && s[i + k] == s[j + k])k++;
		if (s[i + k] < s[j + k])i += k + 1;
		else j += k + 1;
		if (i == j)j++;
		if (i > j)swap(i, j);
	}
	return i;
}
int main() {
	while (cin >> str) {
		int mn = minrepresentation(str);
		int mx = maxrepresentation(str);
		str.insert(0, " ");
		int n = str.length();
		n--;
		for (int i = 2, j = 0; i <= n; i++) {
			while (j && str[i] != str[j + 1])j = ne[j];
			if (str[i] == str[j + 1])j++;
			ne[i] = j;
		}
		int r = n - ne[n];
		int ans = n % r ? 1 : n / r;
		printf("%d %d %d %d\n", mn, ans, mx, ans);
	}
	return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1029402.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Haproxy负载均衡群集

HAproxy搭建Web群集一、Web集群调度器1、常见的Web集群调度器2、常用集群调度器的优缺点&#xff08;LVS ,Nginx,Haproxy)2.1 Nginx2.2 LVS2.3 Haproxy 3、LVS、Nginx、HAproxy的区别 二、Haproxy1、简介2、Haproxy应用分析3、HAProxy的主要特性4、Haproxy调度算法&#xff08;…

智慧云图书馆: 能支撑智慧图书馆服务体系的图书馆管理与服务平台

一、开源项目简介 柏拉图 PLATO 智慧云图书馆&#xff1a; 能支撑智慧图书馆服务体系的图书馆管理与服务平台。 二、开源协议 未使用主流开源协议 三、界面展示 四、功能概述 平台优势 总分馆架构&#xff1a;不再是信息的孤岛&#xff0c;而是共享信息的平台。友好的界…

openGauss学习笔记-76 openGauss 数据库管理-内存优化表MOT管理-内存表特性-MOT简介

文章目录 openGauss学习笔记-76 openGauss 数据库管理-内存优化表MOT管理-内存表特性-MOT简介76 MOT简介 openGauss学习笔记-76 openGauss 数据库管理-内存优化表MOT管理-内存表特性-MOT简介 本节介绍了openGauss内存优化表&#xff08;Memory-Optimized Table&#xff0c;MOT…

spring-boot---validation,参数校验,分组,嵌套,各种类型

写在前面&#xff1a; 参数校验基本上是controller必做的事情&#xff0c;毕竟前端传过来的一切都不可信。 但是每次if(StrUtil.isNotNull())啥的有时候多还难写。validation可以简化这一操作。 文章目录 项目构建问题展示validation使用快速入门注释 Valid与Validated区别使…

【面试必刷TOP101】判断一个链表是否为回文结构 链表的奇偶重排

目录 题目&#xff1a;判断一个链表是否为回文结构_牛客题霸_牛客网 (nowcoder.com) 题目的接口&#xff1a; 解题思路&#xff1a; 代码&#xff1a; 过啦&#xff01;&#xff01;&#xff01; 题目&#xff1a;链表的奇偶重排_牛客题霸_牛客网 (nowcoder.com) 题目的…

Twitter图片数据优化的细节

Twitter个人数据优化&#xff1a;吸引更多关注和互动 头像照片在Twitter上&#xff0c;头像照片是最快识别一个账号的方法之一。因此&#xff0c;请务必使用公司的标志或与品牌相关的图片。建议尺寸为400x400像素。 为了建立强大的品牌形象和一致性&#xff0c;强烈建议在所有…

WebGL 初始化着色器

目录 前言 初始化着色器的7个步骤 创建着色器对象&#xff08;gl.createShader&#xff08;&#xff09;&#xff09; gl.createShader&#xff08;&#xff09;规范 gl.deleteShader&#xff08;&#xff09;规范 指定着色器对象的代码&#xff08;gl.shaderSource&…

大二层—多链接透明互联协议如何工作

大二层就引入了 TRILL&#xff08;Transparent Interconnection of Lots of Link&#xff09;&#xff0c;即多链接透明互联协议。它的基本思想是&#xff0c;二层环有问题&#xff0c;三层环没有问题&#xff0c;那就把三层的路由能力模拟在二层实现。 运行 TRILL 协议的交换…

23062QTday5

完成登录界面的注册功能 头文件 #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QApplication> #include <iostream> #include <QMessageBox> #include <QtDebug> #include <QIcon> #include<QPushButton> #incl…

Leetcode—— 20.有效的括号

20. 有效的括号 给定一个只包括 ‘(’&#xff0c;‘)’&#xff0c;‘{’&#xff0c;‘}’&#xff0c;‘[’&#xff0c;‘]’ 的字符串 s &#xff0c;判断字符串是否有效。 有效字符串需满足&#xff1a; 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭…

【LeetCode-中等题】 222. 完全二叉树的节点个数

文章目录 题目方法一&#xff1a;把该题当做一个普通的二叉树来做&#xff08;任何遍历都可以&#xff09;方法二&#xff1a;利用完全二叉树的性质来做 题目 方法一&#xff1a;把该题当做一个普通的二叉树来做&#xff08;任何遍历都可以&#xff09; 例如&#xff1a;二叉树…

如何选择一只股票,待完善。

目录 ROE(盈利能力)增长率(成长能力)收现比(营收质量)总资产周转率(经营能力)增长率(成长能力)商誉净资产比(排雷)流动比率(排雷) ROE(盈利能力) 什么是ROE? ROE 全名叫 Return of Equity&#xff0c;翻成中文叫“股东回报率”&#xff0c;也叫"净资产收益率"。 …

token登录的实现

token登录的实现 我这种token只是简单的实现token&#xff0c;就是后端利用UUID 生成简单随机码&#xff0c;利用随机码作为在Redis中的键&#xff0c;然后存储的用户信息作为值&#xff0c;在每次合理请求的时候对token的有效时间进行刷新&#xff08;利用拦截器&#xff09;&…

常见的文件格式

一、C:\fakepath\新建文本文档.txt [object String] 实现方式&#xff1a; <input onchange"test(this.value)" type"file"></input><script>function test(e){console.log(e,Object.prototype.toString.call(e))}</script> 二、…

js 数组对象转为 key对应的数组

1、将要转换的格式 2、 转换后格式 3、代码处理 可以使用forEach循环遍历原始数组&#xff0c;并将每个对象的属性值分别存储在一个新的对象中。然后&#xff0c;使用Object.values()方法获取这些属性值的数组。 console.log(result--, result);let dealRes {};result.forEac…

10.12广州见 | 第十六届智慧城市大会报名通道全面开启

第十六届中国智慧城市大会 将于10月12日至13日 在广州举办 智慧城市是数字中国、智慧社会的核心载体&#xff0c;是数字时代城市发展的高级形态。由中国服务贸易协会、中国测绘学会、中国遥感委员会主办的第十六届中国智慧城市大会&#xff0c;将以“数实融合开放创新智引未…

“降本”是关键,FCU1104打造低成本工商业储能EMS

在不久前举行的EESA中国国际储能展上&#xff0c;“工商业储能”成为了热度最高的话题之一&#xff0c;几乎每家展出工商业储能系统的展商都收获了大量观众的驻足围观&#xff0c;热度非凡。究竟是怎样的原因让工商业储能如此瞩目呢&#xff1f; 通过与多家储能厂家沟通并查阅…

群晖管家+内网穿透实现公网远程访问本地黑群晖

白嫖怪狂喜&#xff01;黑群晖也能使用群晖管家啦&#xff01; 文章目录 白嫖怪狂喜&#xff01;黑群晖也能使用群晖管家啦&#xff01;1.使用环境要求&#xff1a;2.下载安装群晖管家app3.随机地址登陆群晖管家app4.固定地址登陆群晖管家app 自己组装nas的白嫖怪们虽然也可以通…

IP转地理位置:探讨技术与应用

IP地址是互联网上设备的唯一标识符&#xff0c;而将IP地址转换为地理位置信息是网络管理、安全监控和市场定位等领域中的一项重要任务。本文将深入探讨IP转地理位置的技术原理和各种应用场景。 IP地址与地理位置 IP地址&#xff08;Internet Protocol Address&#xff09;是一…

一、八大排序(sort)

文章目录 一、时间复杂度&#xff08;一&#xff09;定义&#xff1a;常数操作 二、空间复杂度&#xff08;一&#xff09;定义&#xff1a; 三、排序&#xff08;一&#xff09;选择排序1.定义2.代码3.特性 &#xff08;二&#xff09;冒泡排序1.定义2.代码3.特性 &#xff08…