KMP+EXKMP

目录

KMP

 模板1:

 模板2

例1 字符串匹配例题 - 题目 - Daimayuan Online Judge

代码1(两字符串先求nxt[ ]再求f[ ]):

代码2(字符串合并求nxt):

例2 最小循环覆盖 - 题目 - Daimayuan Online Judge

代码:

例3 [UVA 12467] Secret word - 题目 - Daimayuan Online Judge

代码:

EXKMP

 模板:

例1 字符串匹配例题 - 题目 - Daimayuan Online Judge

 代码:

例2 [CF 126B] Password - 题目 - Daimayuan Online Judge

代码:

G - Blue Jeans

代码:


KMP

用 O(n+m) 时间复杂度解决字符串匹配问题 

计算一个字符串s与p的前缀p[1]…p[j]的最长公共子串的长度

nxt[ j ] = k:k < j 且 p[ 1 ]…p[ k ] 和 p[ j-k+1 ]…p[ j ] 完全相等 

模板1:

#include<bits/stdc++.h>
using namespace std;
int n, m;
int nxt[100001], f[100001];//nxt[i]=j:记录p串以i结尾的长度为j的后缀子串与p串前缀 前j位相等
						   //		   j<i
						   //f[i]=j:p对应的从s[i]起的长度j 
char s[100002], p[100002]; 
void kmp() {
	n = strlen(s + 1); m = strlen(p + 1);
	int j = 0;
	nxt[1] = 0;
	for (int i = 2; i <= m; i++) {
		while (j > 0 && p[j + 1] != p[i])//当j=0时,无法再向前更新
			j = nxt[j];
		if (p[j + 1] == p[i])//当找不到对应相等的字符时j=0
			j++;
		nxt[i] = j;
	}

	j = 0;
	for (int i = 1; i <= n; i++) {//遍历s
		while ((j == m) || (j > 0 && p[j + 1] != s[i]))
			j = nxt[j];
		if (p[j + 1] == s[i])
			j++;
		f[i] = j;
	}
}

 模板2

#include<bits/stdc++.h>
using namespace std;
int n, m, t;
int nxt[200005];
char s[100002], p[200005]; 
void kmp() {
	n = strlen(s + 1);
	m = strlen(p + 1);
	p[m + 1] = '#';
	for (int i = m + 2, j = 1; j <= n; i++, j++)
		p[i] = s[j];
	int j = 0;
	nxt[1] = 0;
	for (int i = 2; i <= n+m+1; i++) {
		while (j > 0 && p[j + 1] != p[i])//当j=0时,无法再向前更新
			j = nxt[j];
		if (p[j + 1] == p[i])//当找不到对应相等的字符时j=0
			j++;
		nxt[i] = j;
	}
}

例1 字符串匹配例题 - 题目 - Daimayuan Online Judge

样例输入

3
abababa
aba
aaaaaa
bb
abcabcab
abcab

样例输出

3
1 3 5
-1
-1
2
1 4

数据规模

对于所有数据,保证 1≤T≤10,1≤|a|,|b|≤10^5,字符串均由小写字母构成。

代码1(两字符串先求nxt[ ]再求f[ ]):

#include<bits/stdc++.h>
using namespace std;
int n, m, t;
int nxt[100001], f[100001];
char s[100002], p[100002]; 
void kmp() {
	n = strlen(s + 1);
	m = strlen(p + 1);
	int j = 0;
	nxt[1] = 0;
	for (int i = 2; i <= m; i++) {
		while (j > 0 && p[j + 1] != p[i])//当j=0时,无法再向前更新
			j = nxt[j];
		if (p[j + 1] == p[i])//当找不到对应相等的字符时j=0
			j++;
		nxt[i] = j;
	}

	j = 0;
	for (int i = 1; i <= n; i++) {//遍历s
		while ((j == m) || (j > 0 && p[j + 1] != s[i]))
			j = nxt[j];
		if (p[j + 1] == s[i])
			j++;
		f[i] = j;
	}
	int ans = 0;
	for (int i = 1; i <= n; i++)
		if (f[i] == m)++ans;
	if (!ans)printf("-1\n-1\n");
	else {
		printf("%d\n", ans);
		for (int i = 1; i <= n; i++)
			if (f[i] == m)
				printf("%d ", i - m + 1);
		printf("\n");
	}
}
int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%s%s", s + 1, p + 1);
		kmp();
	}
	return 0;
}

代码2(字符串合并求nxt):

#include<bits/stdc++.h>
using namespace std;
int n, m, t;
int nxt[200005];
char s[100002], p[200005]; 
void kmp() {
	n = strlen(s + 1);
	m = strlen(p + 1);
	p[m + 1] = '#';
	for (int i = m + 2, j = 1; j <= n; i++, j++)
		p[i] = s[j];
	int j = 0;
	nxt[1] = 0;
	for (int i = 2; i <= n+m+1; i++) {
		while (j > 0 && p[j + 1] != p[i])//当j=0时,无法再向前更新
			j = nxt[j];
		if (p[j + 1] == p[i])//当找不到对应相等的字符时j=0
			j++;
		nxt[i] = j;
	}

	int ans = 0;
	for (int i = m + 2; i <= n + m + 1; i++)
		if (nxt[i] == m)++ans;
	if (!ans)printf("-1\n-1\n");
	else {
		printf("%d\n", ans);
		for (int i = m + 2; i <= n + m + 1; i++)
			if (nxt[i] == m)
				printf("%d ", i - 2 * m);
		printf("\n");
	}
}
int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%s%s", s + 1, p + 1);
		kmp();
	}
	return 0;
}

例2 最小循环覆盖 - 题目 - Daimayuan Online Judge

样例输入1

bcabcabcabcab

样例输出1

3

样例输入2

aaaaaaa

样例输出2

1

数据规模

对于所有数据,保证 1≤|a|≤10^5,字符串均由小写字母构成。

代码:

#include<bits/stdc++.h>
using namespace std;
int n, m, t;
int nxt[200005];
char s[100002], p[200005]; 
void kmp() {
	m = strlen(p + 1);
	int j = 0;
	nxt[1] = 0;
	for (int i = 2; i <= m; i++) {
		while (j && p[j + 1] != p[i])
			j = nxt[j];
		if (p[j + 1] == p[i])j++;
		nxt[i] = j;
	}printf("%d", m - nxt[m]);
}
int main() {

	scanf("%s", p + 1);
	kmp();
	return 0;
}

最小循环节vs最小循环覆盖的区别,最小循环覆盖字符串的最后一段可能不是完整的循环子串

最小循环节长度:len-nxt[len]

 求最小循环节问题_搬砖的小孩有肉吃的博客-CSDN博客_最小循环节

例3 [UVA 12467] Secret word - 题目 - Daimayuan Online Judge

 样例输入

listentothesilence

样例输出

sil

数据规模

对于所有数据,保证 1≤|s|≤10^5,字符串均由小写字母构成。

代码:

#include<bits/stdc++.h>
using namespace std;
int n, m, t;
int nxt[200005];
char s[200005]; 
void kmp() {
	n = strlen(s + 1);
	s[n + 1] = '#';//倒序存入
	for (int i = n * 2 + 1, j = 1; j <= n; j++, i--)
		s[i] = s[j];
	int j = 0;
	nxt[1] = 0;
	for (int i = 2; i <= n * 2 + 1; i++) {
		while (j && s[j + 1] != s[i])
			j = nxt[j];
		if (s[j + 1] == s[i])j++;
		nxt[i] = j;
	}int ans = 0;
	for (int i = n + 2; i <= n * 2 + 1; i++)
		ans = max(ans, nxt[i]);
	for (int i = ans; i > 0; i--)
		printf("%c", s[i]);
}
int main() {

	scanf("%s", s + 1);
	kmp();
	return 0;
}

EXKMP

扩展KMP(Z algorithm):以O(n)时间复杂度求出一个字符串s和它的任意后缀s[i]…s[n]的最长公共前缀的长度

KMP vs EXKMP:next[ ]前者是到字符s[ i ]结束,后者是从字符s[ i ]开始

z[ i ]:表示字符串 s 和后缀 s[ i ]…s[ n ]的最长公共前缀的长度

 模板:

#include <bits/stdc++.h>
using namespace std;
int z[100001], n;
char s[100002];
void exkmp() {
	int L = 1, R = 0;
	z[1] = 0;
	for (int i = 2; i <= n; i++) {
		if (i > R)z[i] = 0;
		else {
			int k = i - L + 1;//当前i在[L,R]的相对位置,即k在[1,R-L+1]的位置
			z[i] = min(z[k], R - i + 1);//当z[k]>R-i+1时,k可向后匹配的位置与R以后的串不一定相等
		}
		//暴力匹配
		while (i + z[i] <= n && s[z[i] + 1] == s[i + z[i]])//i+z[i]存在且可匹配
			z[i]++;
		//更新区间[L,R]
		if (i + z[i] - 1 > R)//从i位置向后匹配可到R之后
			L = i, R = i + z[i] - 1;
	}
}

注意:s[ z[i]+1 ] == s[ i+z[i] ],n=strlen( s+1 ) 

例1 字符串匹配例题 - 题目 - Daimayuan Online Judge

 代码:

#include <bits/stdc++.h>
using namespace std;
int z[200005], n, m, t;
char s[100002],p[200004];
void exkmp() {
	int L = 1, R = 0;
	z[1] = 0;
	n = strlen(s + 1);
	m = strlen(p + 1);
	p[m + 1] = '#';
	for (int i = m + 2, j = 1; j <= n; j++, i++)p[i] = s[j];
	for (int i = 2; i <= n + m + 1; i++) {
		if (i > R)z[i] = 0;
		else {
			int k = i - L + 1;
			z[i] = min(z[k], R - i + 1);
		}
		while (i + z[i] <= n + m + 1 && p[i + z[i]] == p[1 + z[i]])
			z[i]++;
		if (i + z[i] - 1 > R)
			L = i, R = i + z[i] - 1;
	}
	int ans = 0, x = 0;
	for (int i = m+2; i <= n+m+1; i++) {
		if (z[i] == m)ans++;
	}if (!ans)printf("-1\n-1\n");
	else {
		printf("%d\n", ans);
		for (int i = m + 2; i <= n + m + 1; i++)
			if (z[i] == m)printf("%d ", i - m - 1);
		printf("\n");
	}
}
int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%s%s", s + 1, p + 1);
		exkmp();
	}
	return 0;
}

例2 [CF 126B] Password - 题目 - Daimayuan Online Judge

样例输入1

fixprefixsuffix

样例输出1

fix

样例输入2

abcdabc

样例输出2

Just a legend

数据规模

对于所有数据,保证 1≤|s|≤10^6,字符串均由小写字母构成。

代码:

#include <bits/stdc++.h>
using namespace std;
int z[1000005], n;
char s[1000002];
void exkmp() {
	n = strlen(s + 1);
	int L = 1, R = 0;
	z[1] = 0;
	for (int i = 2; i <= n; i++) {
		if (i > R)z[i] = 0;
		else {
			int k = i - L + 1;
			z[i] = min(z[k], R - i + 1);
		}
		while (i + z[i] <= n && s[z[i] + 1] == s[i + z[i]])
			z[i]++;
		if (i + z[i] - 1 > R)
			L = i, R = i + z[i] - 1;
	}
	int x = 0, ans = 0;
	for (int i = 2; i <= n; i++) {
		if (i + z[i] - 1 == n)//满足在后缀出现
			if (x >= z[i])
				ans = max(ans,z[i]);//x一定小于i,x>=z[i]表示该前缀一定在中间出现过
		x = max(x, z[i]);
	}
	if (!ans)printf("Just a legend");
	else for (int i = 1; i <= ans; i++)printf("%c", s[i]);
}
int main() {

	scanf("%s", s + 1);
	exkmp();

	return 0;
}

G - Blue Jeans

The Genographic Project is a research partnership between IBM and The National Geographic Society that is analyzing DNA from hundreds of thousands of contributors to map how the Earth was populated.

As an IBM researcher, you have been tasked with writing a program that will find commonalities amongst given snippets of DNA that can be correlated with individual survey information to identify new genetic markers.

A DNA base sequence is noted by listing the nitrogen bases in the order in which they are found in the molecule. There are four bases: adenine (A), thymine (T), guanine (G), and cytosine (C). A 6-base DNA sequence could be represented as TAGACC.

Given a set of DNA base sequences, determine the longest series of bases that occurs in all of the sequences.

Input

Input to this problem will begin with a line containing a single integer n indicating the number of datasets. Each dataset consists of the following components:

  • A single positive integer m (2 <= m <= 10) indicating the number of base sequences in this dataset.
  • m lines each containing a single base sequence consisting of 60 bases.

Output

For each dataset in the input, output the longest base subsequence common to all of the given base sequences. If the longest common subsequence is less than three bases in length, display the string "no significant commonalities" instead. If multiple subsequences of the same longest length exist, output only the subsequence that comes first in alphabetical order.

Sample

InputcopyOutputcopy
3
2
GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
3
GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
3
CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
no significant commonalities
AGATAC
CATCATCAT

题意:给你几个DNA序列长度为60,以第一个为模板,找到之后的DNA中与模板DNA相同的子序列,且保证子序列最长(长度大于等于3)。

用kmp,以第一个为模板,将其长度由60缩减到3,后续字符串依次与其匹配看

代码:

#include <iostream>
using namespace std;
char text[15][70];
int nxt[70];
void getnxt(char *p, int len) {
    int j = 0;
    memset(nxt, 0, sizeof(nxt));
    nxt[1] = 0;
    for (int i = 2; i <= len; i++) {
        while (j > 0 && p[i] != p[j + 1])
            j = nxt[j];
        //printf("p[i]:%c p[j+1]:%c j:%d\n", p[i], p[j + 1],j);
        if (p[j + 1] == p[i])j++;
        nxt[i] = j;
        //printf("i:%d nxt[%d]:%d\n", i, i, nxt[i]);
    }
}
int kmp(char *s, char *p){
    int len1 = strlen(s+1), len2 = strlen(p+1);
    int j = 0;
    for (int i = 1; i <= len1; i++) {
        while ((j == len2) || (j > 0 && s[i] != p[j + 1]))
            j = nxt[j];
        if (s[i] == p[j + 1])j++;
        if (j == len2)return 1;
    }
    return 0;
}
int main(){

    int T, n, flag1;
    scanf("%d", &T);
    while (T--){
        char ans[70] = { 'Z' };//相当于inf最大
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
            scanf("%s", text[i] + 1);
        
        int len;

        for (len = 60; len >= 3; len--){//模板串的长度,最小为三,暴力枚举
            for (int i = 1; i <= 60 - len+1; i++){//可能有多个符合条件的同长度的符合条件字符串,最多不能超过60-len保证最后一个len长度的字符串
                char p[70];
                strncpy(p+1, text[1] + i, len);//把字符串从第一个字母开使依次后移一个单位,每次都将长度为len的字符串赋给str
                p[len + 1] = '\0';
                //printf("len:%d i:%d %s end\n",len,i,p+1);
                getnxt(p, len);//p作为子串初始化nxt
                //printf("len:%d i:%d end\n", len, i);
                int f = 1;
                for (int j = 2; j <= n; j++){//遍历其他碱基序列
                    //printf("text[%d]:%s", j, text[j]+1);
                    if (!kmp(text[j], p)){//不匹配
                        f = 0;
                        //printf("j:%d text[j]:%s \n", j,text[j]+1);
                        break;
                    }
                }
                if (f && strcmp(ans, p+1) > 0)//全部都能匹配,得到一个字符串赋给ans,ans相当于inf为了得到字典序最小的字符串
                    strcpy(ans, p+1);//len长度的字符串可能有多个
            }
            flag1 = 0;
            if (ans[0] != 'Z'){
                printf("%s\n", ans);//找到了符合条件的字符串输出后结束
                flag1 = 1;
                break;
            }
        }
        if (flag1 == 0)//没找到
            printf("no significant commonalities\n");
    }
    return 0;
}

 Blue Jeans(字符串kmp)_jinzk123的博客-CSDN博客_blue jeans字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值