C-Obtain The String sequence automata

Portal: https://vjudge.net/contest/361562#problem/C

Title

  Multiple sets of examples, give you a string s and a string t and an empty string x, request to add a subsequence of s to x, make x become t, find the number of additions.

Ideas

  Use the nxt array of the sequence automaton paparazzi string s to match the entire t string. When the mismatch, the part that has already been matched successfully is regarded as the addition of a subsequence, and then match from the current mismatch position. If it fails, the output -1 cannot be completed.

AC code

#include<iostream>
#include<string.h>
using namespace std;
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
int T,ans,flag;
char s[maxn],t[maxn];
int nxt[maxn][27];
void init(char *s){
    int len=strlen(s);
    for(int i=0;i<26;i++) nxt[len][i]=inf;
    for(int i=len-1;i>=0;i--){
        for(int j=0;j<26;j++){
            nxt[i][j]=nxt[i+1][j];
        }
        nxt[i][s[i]-'a']=i+1;
    }
}
bool find(char *t){
    int len=strlen(t);
    int pos=-1;
    for(int i=0;i<len;i++){
        pos=nxt[pos+1][t[i]-'a'];
        if(pos==inf) return 0;
    }
    return 1;
}
int main()
{
    cin>>T;
    while(T    --){
        cin>>s>>t;
        ans=1;flag=1;
        init(s);
        int lent=strlen(t),pos=0;
        for(int i=0;i<lent;i++){
            int k=t[i]-'a';
            if(nxt[pos][k]==inf){
                ans++;
                pos=0;
                if(nxt[pos][k]==inf){
                    flag=0;break;
                }
                pos=nxt[pos][k];
            }
            else{
                pos=nxt[pos][k];
            }
        }
        if(flag)
            cout<<ans<<'\n';
        else
            cout<<-1<<'\n';
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/qq2210446939/p/12690410.html