跳到正文

题解

题解:AT_abc477_c [ABC477C] Range Search Query

ZZX__AK约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年9月28日
收录
2026年10月13日
更新
2026年11月13日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前

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。形式化地说:当l≤x≤r−m+1l\le x\le r-m+1时输出Yes,式子不成立时就输出No。

代码实现

代码实现主要分为两部分:找子串t的起始位置和找符合条件的x。

因为n≤4×105n\le4\times10^5和m≤10m\le10的数据范围,所以我们可以暴力找出所有子串t的起始位置,并记录在数组中。复杂度:O(nm)O(nm)。

我们还可以通过lower_bound来查询第一个大于等于l的x,再判断x≤r−m+1x\le r-m+1是否成立。复杂度:O(qlog⁡n)O(q\log{n})。

Code

C++
#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;
}
原文