HDOJ-2087 (KMP algorithm)

Cut fabric strips

HDOJ-2087

This question and hdoj-1686 is similar, the only difference here is that the sub-string must be a separate. Therefore, when determining how many children can not use the string the previous method. But the cycle, just find a substring, not I ++, but the length of the substring + =.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
string a,b,com;
int pi[2010];
void Pi(string s){
    memset(pi,0,sizeof(pi));
    int n=s.length();
    pi[0]=0;
    for(int i=1;i<n;i++){
        int j=pi[i-1];
        while(j>0&&s[i]!=s[j]){
            j=pi[j-1];
        }
        if(s[i]==s[j])
            j++;
        pi[i]=j;
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    while(cin>>b){
        if(b=="#")
        break;
        cin>>a;
        char c=20;
        com=a+c+b;
        Pi(com);
        int n=a.length();
        int m=b.length();
        int ans=0;
        for(int i=n*2;i<n+m+1;){
            if(pi[i]==n){
                ans++;
                i+=n;
            }else{
                i++;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/GarrettWale/p/11325416.html