加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

kmp(多次无重叠匹配)

发布时间:2020-12-13 22:17:17 所属栏目:PHP教程 来源:网络整理
导读:http://acm.hdu.edu.cn/showproblem.php?pid=2087 剪花布条 ? Problem Description 一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢? ? ? Input 输入中含

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

剪花布条

?

Problem Description
一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?
?

?

Input
输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。
?

?

Output
输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。
?

?

Sample Input
abcde a3 aaaaaa aa #
?

?

Sample Output
0 3
?

?

Author
qianneng
?

?

Source
冬练三九之二
?

?

Recommend
lcy???|???We have carefully selected several similar problems for you:?? 1686? 3746? 3336? 1358? 2091
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <algorithm>
#include <iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include <stdio.h>
#include <string.h>
using namespace std;
const int N = 500009 ;
int c[N] ;
int n ;
//int p[220009] ;
char a[1000009] ;
char b[10009];


void getnext(char *b,int *next)
{
    int len = strlen(b);
    int j = 0,k = -1 ;
    next[0] = -1 ;
    while(j < len)//查找多次且可重叠时len不能减一,因为该单词的末尾加一的next也需要被下一次查询用到。
    {
        if(k == -1 || b[k] == b[j])
        {
            k++;
            j++;
            // 下面nest数组的优化
            if(b[k] != b[j])
                next[j] = k ;
            else
                next[j] = next[k];
        }
        else
        {
            k = next[k];
        }
    }
}

int main()
{
    int n ;
    scanf("%d",&n);
    while(n--)
    {
        int next[10009];
        scanf("%s",b);
        scanf("%s",a);
        int lena = strlen(a),lenb = strlen(b);
        getnext(b,next);
        int i = 0,j = 0;
        int ans = 0 ;
        while(i < lena)
        {
            if(j == -1 || a[i] == b[j])
            {
                i++ ;
                j++ ;
            }
            else
            {
                j = next[j];
            }
            if(j == lenb)
            {
                ans++;
                j = next[j] ;
            }
        }
        printf("%dn",ans);
    }



    return 0 ;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读