弱校联萌第一场C 栈+KMP

来源:互联网 发布:线程私有数据 编辑:程序博客网 时间:2024/06/06 16:41

链接:http://acm.bnu.edu.cn/v3/contest_show.php?cid=6865#problem/C

题意:一个长串,一个短串,多次进行某操作,问最后形成的串。某操作:从长串中找到第一个短串,然后删掉短串,再把长串合并(就是删后的两部分)

思路:用栈记录当前栈中后面的字符最长能和短串匹配的长度,用另一个维护栈中的字符。每次从栈中取出上一个最大长度进行匹配,如果完全匹配了就删掉(其实就是KMP的过程,只不过当前位不跟上一位有关,而是跟栈中最后一个有关)。


做的字符串的题目比较少,以至于KMP已经忘得差不多了。再这里再写下现在对KMP的理解。。

kmp是求字符串匹配的,next是当失配的时候使用的,目的就是快速找到下一个可能匹配的位置。也就是如果到了第i位失配了,我要找到和当前第i位不一样的,而且前缀跟第i位之前的那部分匹配的进行尝试,就是next数组的含义

/*上面的东西就是自己写着玩的2333333*/

代码:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <stack>#include <queue>using namespace std;const int maxn = 5*1e6+10;char w[maxn],s[maxn];int next[maxn];void KMP(char x[],int m,int next[]){    int i,j;    j = next[0] = -1;    i = 0;    while(i < m){        while(-1 != j&&x[i] != x[j])j = next[j];        next[++ i] = ++ j;    }}int st[maxn],top,loc[maxn];int main(){    while(~scanf("%s%s",w,s)){        int lw = strlen(w);        int ls = strlen(s);        KMP(w,lw,next);        //for(int i = 0;i < lw;i ++)cout<<next[i];cout<<endl;        top = 0;        int p = -1;//存的是栈中最后面最长匹配到了哪里        for(int i = 0;i < ls;i ++){            while(-1 != p&&s[i] != w[p+1])p = next[p];            if(s[i] == w[p+1])p ++;//cout<<p<<endl;            loc[top] = i;            st[top ++] = p;            if(p == lw-1){                top -= lw;                p = st[top-1];            }        }        for(int i = 0;i < top;i ++){            cout<<s[loc[i]];        }cout<<endl;    }    return 0;}


0 0
原创粉丝点击