CodeForces - 1016B
You are given two strings s s and t t, both consisting only of lowercase Latin letters.
The substring s [ l . . r] s[l..r] is the string which is obtained by taking characters s l , s l + 1 , … , sr sl,sl+1,…,sr without changing the order.
Each of the occurrences of string a a in a string b b is a position i i ( 1 ≤ i ≤ | b | − | a | +1 1≤i≤|b|−|a|+1) such that b [ i . . i + | a | − 1 ] =a b[i..i+|a|−1]=a ( | a | |a| is the length of string a a).
You are asked q q queries: for the i i-th query you are required to calculate the number of occurrences of string t t in a substring s [ l i . . r i] s[li..ri].
Input
The first line contains three integer numbers n n, m m and q q ( 1 ≤ n , m ≤ 103 1≤n,m≤103, 1 ≤ q ≤ 105 1≤q≤105) — the length of string s s, the length of string t t and the number of queries, respectively.
The second line is a string s s ( | s | =n |s|=n), consisting only of lowercase Latin letters.
The third line is a string t t ( | t | =m |t|=m), consisting only of lowercase Latin letters.
Each of the next q q lines contains two integer numbers li li and ri ri ( 1 ≤ l i ≤ r i ≤n 1≤li≤ri≤n) — the arguments for the i i-th query.
Output
Print q q lines — the i i-th line should contain the answer to the i i-th query, that is the number of occurrences of string t t in a substring s [ l i . . r i] s[li..ri].
Examples
Input
10 3 4 codeforces for 1 3 3 10 5 6 5 7
Output
Input
15 2 3 abacabadabacaba ba 1 15 3 4 2 14
Output
Input
3 5 2 aaa baaab 1 3 1 1
Output
Note
In the first example the queries are substrings: " cod", " deforces", " fo" and "for", respectively.
剛開始不會做,是因為只想到了用字首和,沒想到應該怎麼去用,根據題意,只有當string t 全部在在所查區間的時候,答案才加一,
所以說如果從查詢區間的頭部向後遍歷的話,不但要知道從哪個字母開始,還要判斷字串t何時結束,字首和不太好維護。
因此,我們從查詢區間的尾部向前遍歷,只要找到字串t結束的地方,只需要判斷字串t的開頭是否在查詢區間之內即可,這樣的字首和容易維護。
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<string> 5 #include<cmath> 6 #include<algorithm> 7 #include<queue> 8 #include<stack> 9 #include<deque> 10 #include<map> 11 #include<iostream> 12 using namespace std; 13 typedef long longLL; 14 const double pi=acos(-1.0); 15 const double e=exp(1); 16 const int N = 10; 17 18 char con[1009],sub[1009]; 19 int check[1009]; 20 int main() 21 { 22int i,p,j,n,m,q; 23int flag,a,b,ans; 24scanf("%d%d%d",&n,&m,&q); 25scanf(" %s",con+1); 26scanf(" %s",sub+1); 27 28for(i=1;i<=n-m+1;i++) 29{ 30p=1; 31flag=0; 32for(j=i;j<=i+m;j++) 33{ 34if(p>m) 35{ 36flag=1; 37break; 38} 39if(con[j]!=sub[p]) 40break; 41p++; 42} 43if(flag==1) 44check[j-1]=1; 45} 46for(i=1;i<=q;i++) 47{ 48ans=0; 49scanf("%d%d",&a,&b); 50for(j=a;j<=b;j++) 51{ 52if(check[j]==1&&j-(m-1)>=a) 53ans++; 54} 55printf("%d\n",ans); 56} 57return 0; 58 } View Code