Educational Codeforces Round 48 (Rated for Div. 2)----B. Segment Occurrences

        因为n的数据并不是很大,那么对于每一个l和r来说,我们都可以截取到substring然后对每一个这样的串做kmp算法,得到匹配成功的次数。

        不过有点费解,别人的kmp好像是300ms左右,我写的到了1300ms,可能写的不是很优越。

代码如下

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e6 + 10;
int nex[maxn];
int n,m,q,l,r;
string s,t;
void get_next(string t){
    nex[0] = -1;
    for (int i=1; i<m; i++){
        int k = nex[i-1];
        while (k>-1 && t[k+1] != t[i]) k = nex[k];
        if (t[k+1] == t[i]) k++;
        nex[i] = k;
    }
}
int kmp(string now){
    int k = -1,ans = 0;
    for (int i=0; i<now.size(); i++){
        while (k>-1 && now[i]!=t[k+1]) k=nex[k];
        if (now[i]==t[k+1]) k++;
     //   cout << k << ' '<< now << ' ' << t << endl;
        if (k == m-1){
            k=nex[k]; ans++;
        }
    }
    return ans;
}
int main(){
    cin >> n >> m >> q;
    cin >> s >> t;
    get_next(t);
//    for (int i=0; i<2; i++) {
//        cout << nex[i] << endl;
//    }
    for (int i=0; i<q; i++) {
        scanf("%d%d",&l,&r);
        string now;
        for (int i=l-1; i<r; i++)
            now += s[i];
        printf("%d\n",kmp(now));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CCCCTong/article/details/81590706