1. 程式人生 > >Educational Codeforces Round 48 (Rated for Div. 2) B. Segment Occurrences(數組前綴和防TLE)

Educational Codeforces Round 48 (Rated for Div. 2) B. Segment Occurrences(數組前綴和防TLE)

pre segment col -m lan 需要 contest tdi ati

題目鏈接: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; }

Educational Codeforces Round 48 (Rated for Div. 2) B. Segment Occurrences(數組前綴和防TLE)