zoukankan      html  css  js  c++  java
  • 2015 四川省赛 C Censor(哈希 | KMP)

    模式串为子串

    KMP

    /*
    
    @author : victor
    
    */
    
    #include <bits/stdc++.h>
    using namespace std;
    
    
    
    typedef long long ll;
    const int MAX = 5e6 + 7;
    
    int next_[MAX];
    char s1[MAX], s2[MAX], ans[MAX];
    int pos[MAX];
    int l1, l2, cnt;
     
    void get_next(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;
        }
    }
     
    void KMP(){
        int i = 0, j = 0;
        cnt = 0;
        while(s1[i] != '')
        {
            ans[cnt] = s1[i ++];
            while(!(j == -1 || ans[cnt] == s2[j]))
                j = next_[j];
            j ++;
            cnt ++;
            pos[cnt] = j;
            if(j >= l2)
            {
                cnt -= l2;
                j = pos[cnt];
            }
        }
    }
     
    int main()
    {
        while(scanf("%s %s", s2, s1) != EOF)
        {
            l1 = strlen(s1);
            l2 = strlen(s2);
            get_next(s2,l2,next_);
            KMP();
            for(int i = 0; i < cnt; i++)
                printf("%c", ans[i]);
            printf("
    ");
        }
    }
    
    
      
    //    A B C A B C A B C
    // -1 0 0 0 1 2 3 4 5 6
    //    A B C B C C B A C
  • 相关阅读:
    第二周总结
    2019春总结作业
    第二次编程总结
    第四周作业
    第十二周作业
    第十一周作业
    第十周作业
    第九周作业
    第八周作业
    第六周作业
  • 原文地址:https://www.cnblogs.com/DWVictor/p/11312052.html
Copyright © 2011-2022 走看看