hdu 2087 剪花布条 与 hdu 1686 Oulipo

http://acm.hdu.edu.cn/showproblem.php?pid=1686

http://acm.hdu.edu.cn/showproblem.php?pid=2087

对于aaaaa aaa来说:

1686的答案就是2

2087的答案就是1

对于代码实现也只是微微的改动

1686代码:

#include <string>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

char T[10010],S[1000010];
int next[10010];

void makenext(){
    int i=0, j=-1;
    next[0] = -1;
    int len = strlen(T);
    while(i < len){
        if(j == -1 || T[i] == T[j]){
            i++;
            j++;
            if(T[i] != T[j]) next[i] = j;
            else next[i] = next[j];
        }
        else j = next[j];
    }
    return;
}

int KMP(){
    int i=0, j=0, res=0;
    int ls = strlen(S), lt = strlen(T);
    while(i < ls){
        if(j == -1 || S[i] == T[j]){
            i++;
            j++;
        }
        else j = next[j];
        if(j >= lt){
            res++;
            j = next[j];
        }
    }
    return res;
}

int main(){
    int cas;
    scanf("%d",&cas);
    while(cas--){
        scanf("%s%s",T,S);
        makenext();
        int ans = KMP();
        printf("%d\n",ans);
    }
    return 0;
}

2087代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

char T[1010],S[1010];
int next[1010];

void getnext(){
    int i=0, j = -1;
    next[0] = -1;
    int n = strlen(T);
    while(i < n){
        if(j == -1 || T[i] == T[j]){
            i++, j++;
            next[i] = j;
        }
        else j = next[j];
    }
}


int KMP(){
    int i = 0, j = 0, s = 0;
    int LS = strlen(S), LT = strlen(T);
    while(i < LS){
        if(j == -1 || T[j] == S[i]){
            i++;
            j++;
        }
        else j = next[j];
        if(j >= LT){
            j = 0;
            s++;
        }
    } 
    return s;
}

int main(){
    while(scanf("%s%s",S,T) != EOF){
        if(S[0] == '#') break;
        getnext();
        int ans = KMP();
        printf("%d\n",ans);
    }    
    //system("pause");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值