scu4438(KMP)

题目链接:https://cn.vjudge.net/contest/159024#problem/C

 

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<stack>
 4 using namespace std;
 5 const int maxn=5000010;
 6 
 7 char s[maxn],p[maxn];
 8 char out[maxn];
 9 int nex[maxn];
10 int sl,pl;
11 struct node
12 {
13     char c;  //匹配字符
14     int k;  //当前已匹配长度
15     node(char c,int k):c(c),k(k){}
16 };
17 
18 stack<node> ans;
19 
20 void getnex(char p[])
21 {
22     int i=0,j=-1;
23     nex[0]=-1;
24     while(i<pl)
25     {
26         while(j!=-1&&p[i]!=p[j]) j=nex[j];
27         nex[++i]=++j;
28     }
29 }
30 
31 
32 void KMP(char p[],char s[])
33 {
34     while(!ans.empty()) ans.pop();
35     getnex(p);
36     int i=0,j=0;
37     while(i<sl)
38     {
39         while(j!=-1&&s[i]!=p[j]) j=nex[j];
40         i++;j++;
41         ans.push(node(s[i-1],j));
42         if(j>=pl)
43         {
44             int len=pl;
45             while(len--) ans.pop();
46             if(ans.empty()) j=0;
47             else j=ans.top().k;
48         }
49     }
50 }
51 
52 int main()
53 {
54     while(scanf("%s%s",p,s)!=EOF)
55     {
56         sl=strlen(s);
57         pl=strlen(p);
58         KMP(p,s);
59         int cnt=0;
60         while(!ans.empty())
61         {
62             out[cnt++]=ans.top().c;
63             ans.pop();
64         }
65         for(int i=cnt-1;i>=0;i--) putchar(out[i]);
66         puts("");
67 
68     }
69 }

 

posted @ 2017-04-17 17:47  yijiull  阅读(172)  评论(0编辑  收藏  举报