Codeforces 1016B Segment Occurrences(kmp)

题目链接:Segment Occurrences

题意

给定两个字符串:长度为 n n s 串和长度为 m m t 串,有 q q 次询问,每次询问一个区间 [l,r],表示询问在 s s 串的 [l,r] 子串内, t t 字符串在这个子串内出现的次数,下标从 1 开始。

输入

第一行包含 3 3 个整数 n,m,q (1n,m103,1q105),第二行为一个长度为 n n 的字符串 s,第三行为一个长度为 m m 的字符串 t,字符串 s s t 都只包含小写字母,接下去 q q 行每行两个整数 l,r (1lrn)

输出

对于每次询问都输出一个答案。

样例

输入
10 3 4
codeforces
for
1 3
3 10
5 6
5 7
输出
0
1
0
1
提示
三次询问的子串分别为 “cod”, “deforces”, “fo” 和 “for”。
输入
15 2 3
abacabadabacaba
ba
1 15
3 4
2 14
输出
4
0
3
输入
3 5 2
aaa
baaab
1 3
1 1
输出
0
0
题解

kmp O(n2) k m p   O ( n 2 ) 预处理所有区间 [l,r] [ l , r ] 内的答案, O(1) O ( 1 ) 输出。

过题代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;

#define LL long long
const int maxn = 1000 + 100;
int n, m, q, l, r;
int ans[maxn][maxn];
int Next[maxn];
char str1[maxn], str2[maxn];

void get_next(char *s) {
    Next[1] = 0;
    int j = 0;
    for(int i = 2; s[i]; ++i) {
        while(j > 0 && s[i] != s[j + 1]) {
            j = Next[j];
        }
        if(s[i] == s[j + 1]) {
            ++j;
        }
        Next[i] = j;
    }
}

int main() {
    #ifdef Dmaxiya
        freopen("test.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    #endif // Dmaxiya
    ios::sync_with_stdio(false);

    while(scanf("%d%d%d", &n, &m, &q) != EOF) {
        scanf("%s%s", str1 + 1, str2 + 1);
        get_next(str2);
        for(int i = 1; i <= n; ++i) {
            int j = 0;
            int ret = 0;
            for(int ii = i; str1[ii]; ++ii) {
                while(j > 0 && str1[ii] != str2[j + 1]) {
                    j = Next[j];
                }
                if(str1[ii] == str2[j + 1]) {
                    ++j;
                }
                if(str2[j + 1] == '\0') {
                    ++ret;
                    j = Next[j];
                }
                ans[i][ii] = ret;
            }
        }
        while(q--) {
            scanf("%d%d", &l, &r);
            printf("%d\n", ans[l][r]);
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值