码迷,mamicode.com
首页 > 其他好文 > 详细

C - Obtain The String 序列自动机

时间:2020-04-13 12:08:06      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:std   代码   problem   pos   cout   color   匹配   i++   http   

传送门:https://vjudge.net/contest/361562#problem/C

题意

  多组样例,给你一个串s和串t还有一个空串x,要求往x里添加s的子序列,使x变为t,求添加次数。

思路

  使用序列自动机狗仔串s的nxt数组,把整个t串进行匹配,当失配的时候,把前面已经匹配成功的部分当成一次子序列的添加,再从当前失配位置从头匹配,如果还是匹配失败则无法完成输出-1.

AC代码

#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;
}

 

C - Obtain The String 序列自动机

标签:std   代码   problem   pos   cout   color   匹配   i++   http   

原文地址:https://www.cnblogs.com/qq2210446939/p/12690410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!