codeforces 1016B. Segment Occurrences

  这题我打cf的时候用暴力,每次询问都用strstr查找l到r区间t的个数,结果t了。。。

  方法1:

后来看了大佬的代码用的是substr函数预先处理,标记了t的起始位置。然后查询时从扫一遍就行了。还是太菜了

#include<string.h>
#include<iostream>
using namespace std;
int n,m,q,a[1000+10];
int main()
{
    string s,t;
    cin>>n>>m>>q;
    cin>>s>>t;
    for(int i=0;i<n-m+1;i++)//预处理,如果i位置为t的起始位置,则a[I]=1;
        if(s.substr(i,m)==t) a[i]=1;
    while(q--)
    {
        int l,r;
        int ans=0;
        cin>>l>>r;
        l--;
        r--;
        for(int i=l;i<=r-m+1;i++)
            if(a[i]) ans++;
        cout<<ans<<endl;

    }
    return 0;
}

方法2:

用了前缀和,和方法1都是预处理了,不过方法2要快一些,因为查询区间不用遍历一遍,可以直接输出。

#include<bits/stdc++.h>
using namespace std;
int pre[1000+10];//pre[i]表示的是s[1]到s[i],t的起始字符的个数,则表示s[1]到s[i+m-1]区间里字符串t的个数
string s,t;
int n,m,q;
int flag;
int main()
{
    cin>>n>>m>>q;
    cin>>s>>t;
    s=" "+s;
    t=" "+t;
    for(int i=1;i<=n;i++)//严谨点的话应该是从1位置遍历到n-m+1,因为最后一个可能等于t的子串是n-m+1到m这个长度为m的子串,即N-M+1位置是最后一个可能是t的起始字符位置的位置但是不能把遍历终点该成n+m-1,因为n-m+1位置后面的字符也是有相应的pre值的
    {
        flag=1;//默认i位置是t的起始字符位置;
        for(int j=1;j<=m;j++)
            if(s[i+j-1]!=t[j])
            {
                flag=0;
                break;
            }
        if(flag)
            pre[i]=pre[i-1]+1;
        else
            pre[i]=pre[i-1]+0;



    }
    while(q--)
    {
        int low,up;
        cin>>low>>up;
        if(up-m+1<1)//特判一下如果区间长度小于m的话就必定不存在t,如果不特判会出现pre[-1],还有(pre[4]-pre[6]),这种不合法的情况
            cout<<0<<endl;
        else
            if(up-m+1<low)
                cout<<0<<endl;
            else
                cout<<pre[up-m+1]-pre[low-1]<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/eason9906/p/11755003.html