您的位置:首页 > 产品设计 > UI/UE

LIGHTOJ 1255-SUBSTRING FREQUENCY 【KMP】

2015-06-05 23:24 591 查看
题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1255

题意:求母串中包含子串的个数,可重叠。

代码:

[code]#include <stdio.h>  
#include <iostream>  
#include <math.h>  
#include <stdlib.h>  
#include <ctype.h>  
#include <algorithm>  
#include <vector>  
#include <string.h>  
#include <queue>  
#include <stack>  
#include <set>  
#include <map>  
#include <sstream>  
#include <time.h>  
#include <malloc.h>  

using namespace std;

void get_next(char x[], int m, int Next[])
{
    int i, j;
    j = Next[0] = -1;
    i = 0;
    while (i < m)
    {
        while (-1 != j && x[i] != x[j]) j = Next[j];
        Next[++i] = ++j;
    }
}

int Next[1001000];
long long KMP(char x[], int m, char y[], int n)//x模式串 y主串
{
    int i, j;
    long long ans = 0;
    i = j = 0;
    get_next(x, m, Next);
    while (i < n)
    {
        while (-1 != j && y[i] != x[j])
            j = Next[j];
        i++; j++;
        if (j >= m)
        {
            ans++;
            j = Next[j];
        }
    }
    return ans;
}
char a[1000100], b[1000100];

int main()
{
    int t, num;
    scanf("%d", &t);
    for (int i = 1; i <= t; i++)
    {
        printf("Case %d: ", i);
        scanf("%s", a);
        int n = strlen(a);
        scanf("%s", b);
        int m = strlen(b);
        printf("%lld\n", KMP(b, m, a, n));

    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: