Educational Codeforces Round 48 (Rated for Div. 2) B. Segment Occurrences(数组前缀和防TLE)

题目链接:http://codeforces.com/contest/1016/problem/B

给两个字符串s,t,之后给出s的一个区间,问这个子串中存在多少个子串与t相同

如果一个一个查找就会超时,因此只需要把前缀和相减即可

#include <bits/stdc++.h>

using namespace std;


int n,m,q;
string s,t;
int l,r;
int hay[10000],shay[10000];

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>q;
    cin>>s>>t;
    s=" "+s;
    t=" "+t;
    for(int i=1;i<=n-m+1;i++)
    {
        hay[i]=1;
        for(int j=0;j<m;j++)
        {
            if(s[i+j]!=t[1+j])
            {
                hay[i]=0;
                break;
            }
        }
        shay[i]=shay[i-1]+hay[i];
    }

    while(q--)
    {
        cin>>l>>r;
        r=r-m+1;
        if(r<l) cout<<"0"<<endl;
        else cout<<shay[r]-shay[l-1]<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Fy1999/p/9417082.html