题解:P16104 [ICPC 2019 NAIPC] Subsequences in Substrings

· · 题解

P16104 题解:

主要思路:

贪心枚举左右端点,如果当前子串中存在满足条件的子序列就更新答案。

代码实现:

从字符串 s 中枚举左右端点,如果当前子串中存在子序列 t,就让答案加上 s.size()-v,其中 v 为右端点(如果当前序列满足条件,就可以随便往后加字母),最后输出答案即可。

#include <bits/stdc++.h>
#define int long long
using namespace std;
string s,t;
int32_t main(){
    cin.tie(nullptr)->ios::sync_with_stdio(false);
    cin>>s;
    cin>>t;
    int ans=0;
    for(int i=0;i<s.size();i++){
        int p=0,v=0;
        for(int j=i;j<s.size();j++){
            if(p<t.size()&&s[j]==t[p]){
                p++;
            }
            if(p==t.size()){
                v=j;
                break;
            }
        }
        if(p==t.size()) ans+=s.size()-v;
    }
    cout<<ans;
    return 0;
}