scu 4438 Censor

之前做过类似的题目,不过因为匹配串长度较短,所以都是直接模拟的,而此题字符串的长度比较长,所以我们得用KMP。
先用KMP得到匹配串w的next数组,然后匹配两个串,边匹配边用栈模拟,栈维护主串每次匹配到匹配串的哪个位置,然后如果匹配到了整个串,那么将栈顶的 |匹配串 |全部删除,然后使得匹配串的位置移动到当初记录的位置,继续与主串进行匹配。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#define ONLINE_JUDGE
#define eps 1e-5
#define INF 0x7fffffff
#define FOR(i,a) for((i)=0;i<(a);(i)++)
#define MEM(a) (memset((a),0,sizeof(a)))
#define sfs(a) scanf("%s",a)
#define sf(a) scanf("%d",&a)
#define sfI(a) scanf("%I64d",&a)
#define pf(a) printf("%d\n",a)
#define pfI(a) printf("%I64d\n",a)
#define pfs(a) printf("%s\n",a)
#define sfd(a,b) scanf("%d%d",&a,&b)
#define sft(a,b,num) scanf("%d%d%d",&a,&b,&num)
#define for1(i,a,b) for(int i=(a);i
#define for2(i,a,b) for(int i=(a);i<=b;i++)
#define for3(i,a,b)for(int i=(b);i>=a;i--)
#define MEM1(a) memset(a,0,sizeof(a))
#define MEM2(a) memset(a,-1,sizeof(a))
#define ll long long
const double PI=acos(-1.0);
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T Min(T a,T b){return atemplate<class T> inline T Max(T a,T b){return a>b?a:b;}
using namespace std;
//#pragma comment(linker,"/STACK:1024000000,1024000000")
int n,m,x;
#define N 5000010
#define M 100010
#define Mod 1000000000
#define p(x,y) make_pair(x,y)
const int MAX_len=550;
char w[N];
char p[N];
int next[N];
struct Node{
    char c;
    int pos;
};
void getNext(){
    next[0]=-1;
    int j=0,k=-1;
    int len = strlen(w);
    while(jif(k == -1 || w[j] == w[k]){
            k++;
            j++;
            if(w[j] != w[k])
                next[j] = k;
            else
                next[j] = next[k];
        }else
            k = next[k];
    }
}
void KMP(){
    int len1 = strlen(p);
    int len2 = strlen(w);
    if(len1printf("%s\n",p);
        return;
    }
    stack s;
    int i=0,j=0;
    while(iif(j == -1 || p[i] == w[j]){
            j++;
            i++;
            s.push((Node){p[i-1],j});//记录下该位置的字符和其匹配到的位置
        }else
            j = next[j];
        if(j>=len2){
            int tmp = len2;
            while(tmp--) s.pop();   //将栈顶的len2个字符全部删除
            if(s.empty()) j=0;  //如果栈空了,那么匹配串重新匹配
            else
                j = s.top().pos;//否则主串将继续与匹配串的pos位置匹配
        }
    }
    vector<char> v;
    while(!s.empty()){
        v.push_back(s.top().c);
        s.pop();
    }
    int size = (int)v.size();
    for(int i=size-1;i>=0;i--)
        printf("%c",v[i]);
    printf("\n");
}
int main(){
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
//  freopen("out.txt", "w", stdout);
#endif
    while(scanf("%s%s",w,p)!=EOF){
        getNext();
        KMP();
    }
    return 0;
}

你可能感兴趣的:(字符串)