【hiho一下 第三周】KMP算法

【题目链接】:http://hihocoder.com/problemset/problem/1015

【题意】

【题解】

把f数组,len1,len2数组一开始全都定义成char型
这酸爽.

【Number Of WA

3

【完整代码】

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 1e6+100;

char s1[N],s2[N];
int f[N],len1,len2;

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    int t;
    cin >> t;
    while (t--)
    {
        int ans = 0;
        scanf("%s",s1);
        scanf("%s",s2);
        len1 = strlen(s1),len2 = strlen(s2);
        f[0] = f[1] = 0;
        rep1(i,1,len1-1)
        {
            int j = f[i];
            while (j && s1[i]!=s1[j]) j = f[j];
            f[i+1]=(s1[i]==s1[j])?(j+1):0;
        }
        int j = 0;
        rep1(i,0,len2-1)
        {
            while (j && s2[i]!=s1[j]) j = f[j];
            if (s2[i]==s1[j])
            {
                j++;
                if (j==len1)
                {
                    ans++;
                    j = f[j];
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626355.html