ZOJ3587 Marlon's String

KMP,正着处理一遍,反着处理一遍,但是用递归的方式一个一个统计会超时,最后累加一下比较好= =


#include <cstdio>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;

void getnext(char *s, int *next)
{
    int i = 0, j = -1, l = strlen(s);
    next[0] = -1;
    while (i < l)
    {
        if (j == -1 || s[i] == s[j])
        {
            i++; j++;
            next[i] = j;
            //if (s[i] == s[j]) next[i] = j;
            //else next[i] = -1;
        }
        else j = next[j];
    }
}

void find(char *s, char *t, int *next, int *a)
{
    int l = strlen(s), n = strlen(t), i = 0, j = 0;
    while (i < l && j < n)
    {
        if (j == -1 || s[i] == t[j])
        {
            i++; j++;
            a[j]++;
        }
        else j = next[j];
    }
}

const int maxn = 100005;
int T, n, l;
char s[maxn], t[maxn];
int next[maxn], a[maxn], b[maxn];
long long ans;

int main()
{
    scanf("%d", &T);
    while (T--)
    {
        scanf("%s%s", s, t);
        l = strlen(s); n = strlen(t);
        t[n] = '$'; t[n+1] = 0;

        memset(a, 0, sizeof(a));
        getnext(t, next);
        find(s, t, next, a);
        for (int i=n;i>=1;i--)
            if (next[i] != -1)
                a[next[i]] += a[i];

        for (int i=0;i<l/2;i++) swap(s[i], s[l-i-1]);
        for (int i=0;i<n/2;i++) swap(t[i], t[n-i-1]);
        memset(b, 0, sizeof(b));
        getnext(t, next);
        find(s, t, next, b);
        for (int i=n;i>=1;i--)
            if (next[i] != -1)
                b[next[i]] += b[i];

        ans = 0;
        for (int i=1;i<n;i++)
            ans += (long long)a[i] * b[n-i];
        printf("%lld\n", ans);
    }
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值