跳到正文

题解

题解:P12422 【MX-X12-T5】「ALFR Round 5」Another string problem

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

文章信息

发布
2025年5月7日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 2 分钟
获赞
6
题目
P12422

版本

  1. v1当前

题意

求 ⌊∣T∣/∣S∣⌋\lfloor |T|/|S| \rfloor 个 SS 相连的字符串是不是 TT 的子序列。

思路

先考虑暴力求解,但时间复杂度高达 O(∑(∣T∣×q))O(\sum (\lvert T\rvert \times q))。

于是考虑优化,我们发现:当 TT 和 ⌊∣T∣/∣S∣⌋\lfloor |T|/|S| \rfloor 个 SS 相连的字符串匹配过的字符数差大于他们的长度差时,⌊∣T∣/∣S∣⌋\lfloor |T|/|S| \rfloor 个 SS 相连的字符串就一定不是 TT 的子序列。

但是,现在的时间复杂度依旧很高。根据上面发现的规律,若匹配到字符串的后面时,此时的时间复杂度就会很高。但是满足的字符串 SS 较少,因此我们考虑使用 unordered_map 进行记忆化。

代码

C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;

int T;
char s[N],t[N];

signed main(){
	scanf("%d",&T);
	while(T--){
		unordered_map<string,bool> m;
		int q;
		scanf("%s%d",s,&q);
		int s1=strlen(s);
		while(q--){
			scanf("%s",t);
			string b=t;
			if(m.count(b)){
				if(m[b]) printf("Yes\n");
				else printf("No\n");
				continue;
			}
			int t1=strlen(t);
			int f2=s1/t1;
			int f1=f2*t1;
			int i,j,k,o;
			for(i=0,j=0,k=0,o=0;i<s1 && k<f2;i++){
				if(i-o>s1-f1) break;//优化循环次数 
				if(s[i]==t[j]){
					j++;
					o++;
					if(j==t1) j=0,k++;
				}
			}
			if(k>=f2) printf("Yes\n");
			else printf("No\n");
			m[t]=(k>=f2);//记忆化 
		}
	}

	return 0;
}

最慢的点时间为:153ms。

原文
存档评论2 条抓取于