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

· · 题解

题意

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

思路

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

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

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

代码

#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。