KMP常用算法模板

来源:互联网 发布:媒体矩阵 是什么意思 编辑:程序博客网 时间:2024/06/05 05:15

1.求主串中模式串出现了几次

例题 HDU1686

#include<cstdio>#include<cstring>using namespace std;#define EPS 1e-7#define clr(x) memset(x, 0, sizeof(x))#define long long ll#define double db#define PI acos(-1.0)const int INF = 0x3f3f3f3f;const int MOD=1000000007;const int MAXN = 10000000;const int dx[] = {1, -1, 0, 0};const int dy[] = {0, 0, 1, -1};int next[MAXN];char str1[MAXN];char str2[MAXN];int ans;void getnext(char x[], int m){    int i = 0, j = next[0] = -1;    while(i < m)    {        while(j != -1 && x[j] != x[i])            j = next[j];        next[++i] = ++j;    }}void kmp(char x[], char y[], int n, int m){    int i = 0, j = 0;    while(i < n)    {        while(j != -1 && x[j] != y[i])            j = next[j];            i++; j++;            if(j == m)            {                ans++;                j = next[j];            }    }}int main(){    int t;    scanf("%d", &t);    while(t--)    {        ans = 0;        clr(str1);        clr(str2);        scanf("%s %s", str1, str2);        int m = strlen(str1);        int n = strlen(str2);        getnext(str1, m);        kmp(str1, str2, n, m);        printf("%d\n", ans);    }    return 0;}

2.求主串中模式串出现的位置

HDU1711

#include<cstdio>#include<cstring>using namespace std;#define EPS 1e-7#define clr(x) memset(x, 0, sizeof(x))#define long long ll#define double db#define PI acos(-1.0)const int INF = 0x3f3f3f3f;const int MOD=1000000007;const int MAXN = 1000000 + 5;const int dx[] = {1, -1, 0, 0};const int dy[] = {0, 0, 1, -1};int next[MAXN];int str1[MAXN];int str2[MAXN];int ans;void getnext(int x[], int m){    int i = 0, j = next[0] = -1;    while(i < m)    {        while(j != -1 && x[j] != x[i])            j = next[j];        next[++i] = ++j;    }}void kmp(int x[], int y[], int n, int m){    int i = 0, j = 0;    while(i < n)    {        while(j != -1 && x[j] != y[i])            j = next[j];            i++; j++;            if(j == m)            {               ans = i - m + 1;               return ;            }    }}int main(){    int t;    scanf("%d", &t);    while(t--)    {        ans = -1;        clr(str1);        clr(str2);        int n, m;        scanf("%d %d", &n, &m);        for(int i = 0; i < n; i++)            scanf("%d", &str2[i]);        for(int j = 0; j < m; j++)            scanf("%d", &str1[j]);        getnext(str1, m);        kmp(str1, str2, n, m);        printf("%d\n", ans);    }    return 0;}


0 0
原创粉丝点击