Codeforces #1016B: Segment Occurences 题解

Description

You are given two strings s and t, both consisting only of lowercase Latin letters.The substring s[l..r] is the string which is obtained by taking characters sl,sl+1,…,sr without changing the order.Each of the occurrences of string a in a string b is a position 1≤i≤|b|−|a|+1) such that b[i..i+|a|−1]=a (|a| is the length of string a).You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[li..ri].

Input

The first line contains three integer numbers n, m and q (1≤n,m≤1e3, 1≤q≤1e5) — the length of string s, the length of string t and the number of queries, respectively.
The second line is a string s (|s|=n), consisting only of lowercase Latin letters.
The third line is a string t (|t|=m), consisting only of lowercase Latin letters.
Each of the next q lines contains two integer numbers (1≤li≤ri≤n) — the arguments for the i-th query.

Output

Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[li..ri].


显然可以先用 O(n2) O ( n 2 ) 的时间找出t在s中出现的所有的位置
然后对于一个区间l,r的查询,只要在位置数组中二分一下就好了

#include 
using namespace std;

#define LL long long
#define LB long double
#define ull unsigned long long
#define x first
#define y second
#define pb push_back
#define pf push_front
#define mp make_pair
#define Pair pair
#define pLL pair
#define pii pair

const int INF=2e9;
const LL LINF=2e16;
const int magic=348;
const int MOD=998244353;
const double eps=1e-10;
const double pi=acos(-1);

inline int getint()
{
    bool f;char ch;int res;
    while (!isdigit(ch=getchar()) && ch!='-') {}
    if (ch=='-') f=false,res=0; else f=true,res=ch-'0';
    while (isdigit(ch=getchar())) res=res*10+ch-'0';
    return f?res:-res;
}

const int MAXN=1e5;

char s[1048],t[1048];int n,m,q;

int a[1048],tot=0;

inline bool check_same(int pos)
{
    int i;
    for (i=1;i<=m;i++) if (t[i]!=s[pos+i-1]) return false;
    return true;
}

inline int bsearch1(int pos)
{
    int l=1,r=tot,mid,res=tot+1;
    while (l<=r)
    {
        mid=(l+r)>>1;
        if (a[mid]>=pos) res=mid,r=mid-1; else l=mid+1;
    }
    return res;
}

inline int bsearch2(int pos)
{
    int l=1,r=tot,mid,res=0;
    while (l<=r)
    {
        mid=(l+r)>>1;
        if (a[mid]<=pos) res=mid,l=mid+1; else r=mid-1;
    }
    return res;
}

int main ()
{
    n=getint();m=getint();q=getint();
    scanf("%s",s+1);scanf("%s",t+1);int i;
    for (i=1;i<=n-m+1;i++)
        if (check_same(i)) a[++tot]=i;
    while (q--)
    {
        int l=getint(),r=getint();
        if (r-l+1puts("0");continue;}
        r=r-m+1;
        int pos1=bsearch1(l),pos2=bsearch2(r);
        printf("%d\n",pos2-pos1+1);
    }
    return 0;
}

你可能感兴趣的:(二分,Codeforces,字符串,二分)