题解:AT_abc477_c [ABC477C] Range Search Query
AT_abc477_c [ABC477C] Range Search Query题解
思路概述
题目给出两个字符串s和t,有q次询问,每次询问在 s[l]到s[r]的区间内有没有子串t。
我们设s的长度为n,设t的长度为m我们可以获取在字符串s中子串t的起始位置x,所以每次询问时只要有一个子串在l到r范围内即输出Yes,否则即输出No。形式化地说:当
代码实现
代码实现主要分为两部分:找子串t的起始位置和找符合条件的x。
因为
我们还可以通过lower_bound来查询第一个大于等于l的x,再判断
Code
#include<bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int q;
string s,t;
cin>>q>>s>>t;
int n=s.size();
int m=t.size();
vector<int> pos;
for(int i=0; i<=n-m; i++) {
bool ok=1;
for(int j=0; j<m; j++) {
if(s[i+j]!=t[j]) {
ok=false;
break;
}
}
if(ok) {
pos.push_back(i+1);
}
}
while(q--) {
int l,r;
cin>>l>>r;
if (r-l+1<m) {
cout<<"No\n";
continue;
}
int last=r-m+1;
auto it=lower_bound(pos.begin(),pos.end(),l);
if(it!=pos.end()&& *it<=last) {
cout<<"Yes\n";
} else {
cout<<"No\n";
}
}
return 0;
}