KMP练习(一)

1 篇文章 0 订阅
1 篇文章 0 订阅

A - Number Sequence(hdu1711

Problem Description

Given two sequences of numbers : a[1], a[2], …… , a[N], and b[1], b[2], …… , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], …… , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.

Input

The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], …… , a[N]. The third line contains M integers which indicate b[1], b[2], …… , b[M]. All integers are in the range of [-1000000, 1000000].

Output

For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.

Sample Input

2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1

Sample Output

6
-1 

Source

HDU 2007-Spring Programming Contest

Solve

题目大意就是给你两列数,要你找到第一列数中最开始包含第二列数的位置,如果找不到就返回-1。类似于字符串的匹配,直接可以使用KMP进行匹配。

#include <iostream>
#include <string>
#include <vector>

int KMP(const std::vector<int> &text,
             const std::vector<int> &pattern) {
    int textLength = text.size();
    int patternLength = pattern.size();
    std::vector<int> next(patternLength, 0);
    for(int i = 1, j = 0; i < patternLength; ++i) {
        while(j && pattern[i] != pattern[j])
            j = next[j - 1];
        if(pattern[i] == pattern[j])
            ++j;
        next[i] = j;
    }
    for(int i = 0, j = 0; i < textLength; ++i) {
        while(j && text[i] != pattern[j])
            j = next[j - 1];
        if(text[i] == pattern[j])
            ++j;
        if(j == patternLength)
            return i - patternLength + 2;
    }
    return -1;
}

int main() {
    auto cnt = 0;
    std::cin >> cnt;
    while(cnt--) {
        auto textLength = 0, patternLength = 0;
        std::cin >> textLength >> patternLength;
        std::vector<int> text, pattern;
        while(textLength--) {
            int textElem;
            std::cin >> textElem;
            text.push_back(textElem);
        }
        while(patternLength--) {
            int patternElem;
            std::cin >> patternElem;
            pattern.push_back(patternElem);
        }
        std::cout << KMP(text, pattern) << std::endl;
    }
}

B - Oulipo(hdu1686

Problem Description

The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter ‘e’. He was a member of the Oulipo group. A quote from the book:
Tout avait Pair normal, mais tout s’affirmait faux. Tout avait Fair normal, d’abord, puis surgissait l’inhumain, l’affolant. Il aurait voulu savoir où s’articulait l’association qui l’unissait au roman : stir son tapis, assaillant à tout instant son imagination, l’intuition d’un tabou, la vision d’un mal obscur, d’un quoi vacant, d’un non-dit : la vision, l’avision d’un oubli commandant tout, où s’abolissait la raison : tout avait l’air normal mais…
Perec would probably have scored high (or rather, low) in the following contest. People are asked to write a perhaps even meaningful text on some subject with as few occurrences of a given “word” as possible. Our task is to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the competitors. These competitors often write very long texts with nonsense meaning; a sequence of 500,000 consecutive ‘T’s is not unusual. And they never use spaces.
So we want to quickly find out how often a word, i.e., a given string, occurs in a text. More formally: given the alphabet {‘A’, ‘B’, ‘C’, …, ‘Z’} and two finite strings over that alphabet, a word W and a text T, count the number of occurrences of W in T. All the consecutive characters of W must exactly match consecutive characters of T. Occurrences may overlap.

Input

The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:
One line with the word W, a string over {‘A’, ‘B’, ‘C’, …, ‘Z’}, with 1 ≤ |W| ≤ 10,000 (here |W| denotes the length of the string W).
One line with the text T, a string over {‘A’, ‘B’, ‘C’, …, ‘Z’}, with |W| ≤ |T| ≤ 1,000,000.

Output

For every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word W in the text T.

Sample Input

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

Sample Output

1
3
0

Source

华东区大学生程序设计邀请赛_热身赛

Solve

题目看起来真的很长,其实就是个简单的问题,字符串A在字符串B中出现了几次, 允许重叠 ,也就是如果字符串在0位置匹配成功,字符串A长度是n,在1位置匹配成功也算一次,而不重叠的情况就不算。

#include <iostream>
#include <string>
#include <vector>

int KMPCount(const std::string &text,
             const std::string &pattern) {
    int textLength = text.size();
    int patternLength = pattern.size();
    std::vector<int> next(patternLength, 0);
    for(int i = 1, j = 0; i < patternLength; ++i) {
        while(j && pattern[i] != pattern[j])
            j = next[j - 1];
        if(pattern[i] == pattern[j])
            ++j;
        next[i] = j;
    }
    int result = 0;
    for(int i = 0, j = 0; i < textLength; ++i) {
        while(j && text[i] != pattern[j])
            j = next[j - 1];
        if(text[i] == pattern[j])
            ++j;
        if(j == patternLength) {
            ++result;
            j = next[j - 1];
        }
    }
    return result;
}

int main() {
    auto cnt = 0;
    std::cin >> cnt;
    while(cnt--) {
        std::string pattern, text;
        std::cin >> pattern >> text;
        std::cout << KMPCount(text, pattern) << std::endl;
    }
}

C - 剪花布条(hdu2087)

Problem Description

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

Input

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

Output

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

Sample Input

abcde a3
aaaaaa  aa
#

Sample Output

0
3

Author

qianneng

Source

冬练三九之二

Solve

和B题很相似, 只不过是个不重叠的情况。

#include <iostream>
#include <string>
#include <vector>

int KMPCount(const std::string &text,
             const std::string &pattern) {
    int textLength = text.size();
    int patternLength = pattern.size();
    std::vector<int> next(patternLength, 0);
    for(int i = 1, j = 0; i < patternLength; ++i) {
        while(j && pattern[i] != pattern[j])
            j = next[j - 1];
        if(pattern[i] == pattern[j])
            ++j;
        next[i] = j;
    }
    int result = 0;
    for(int i = 0, j = 0; i < textLength; ++i) {
        while(j && text[i] != pattern[j])
            j = next[j - 1];
        if(text[i] == pattern[j])
            ++j;
        if(j == patternLength) {
            ++result;
            j = 0;
        }
    }
    return result;
}

int main() {
    while(true) {
        std::string text, pattern;
        std::cin >> text;
        if(text[0] == '#') break;
        std::cin >> pattern;
        std::cout << KMPCount(text, pattern) << std::endl;
    }
}

D - Cyclic Nacklace(hdu3746)

Problem Description

CC always becomes very depressed at the end of this month, he has checked his credit card yesterday, without any surprise, there are only 99.9 yuan left. he is too distressed and thinking about how to tide over the last days. Being inspired by the entrepreneurial spirit of “HDU CakeMan”, he wants to sell some little things to make money. Of course, this is not an easy task.
As Christmas is around the corner, Boys are busy in choosing christmas presents to send to their girlfriends. It is believed that chain bracelet is a good choice. However, Things are not always so simple, as is known to everyone, girl’s fond of the colorful decoration to make bracelet appears vivid and lively, meanwhile they want to display their mature side as college students. after CC understands the girls demands, he intends to sell the chain bracelet called CharmBracelet. The CharmBracelet is made up with colorful pearls to show girls’ lively, and the most important thing is that it must be connected by a cyclic chain which means the color of pearls are cyclic connected from the left to right. And the cyclic count must be more than one. If you connect the leftmost pearl and the rightmost pearl of such chain, you can make a CharmBracelet. Just like the pictrue below, this CharmBracelet’s cycle is 9 and its cyclic count is 2:(图略)
Now CC has brought in some ordinary bracelet chains, he wants to buy minimum number of pearls to make CharmBracelets so that he can save more money. but when remaking the bracelet, he can only add color pearls to the left end and right end of the chain, that is to say, adding to the middle is forbidden.
CC is satisfied with his ideas and ask you for help.

Input

The first line of the input is a single integer T ( 0 < T <= 100 ) which means the number of test cases.
Each test case contains only one line describe the original ordinary chain to be remade. Each character in the string stands for one pearl and there are 26 kinds of pearls being described by ‘a’ ~’z’ characters. The length of the string Len: ( 3 <= Len <= 100000 ).

Output

For each case, you are required to output the minimum count of pearls added to make a CharmBracelet.

Sample Input

3
aaa
abca
abcde

Sample Output

0
2
5

Author

possessor WC

Source

HDU 3rd “Vegetable-Birds Cup” Programming Open Contest

Solve

题目依旧很长,大意是给你一个字符串A,问要你补充多少个字符,才能让该串的子串重复N次可以得到该串。主要是要求得每个串的循环节,可以通过KMP中的next数组来求得,next[i]表示的是串A[0…i]前缀和后缀相同的最大长度,所以我们直接通过next数组最后一项就可以判断串的循环节,通过A.size()-next[A.size()]可以得到循环节的长度。

#include <cstdio>
#include <cstring>

const int maxn = 100010;
int next[maxn];

int getNextLast(char * str) {
    int strLength = strlen(str);
    next[0] = 0;
    for(int i = 1, j = 0; i < strLength; ++i) {
        while(j && str[i] != str[j])
            j = next[j - 1];
        if(str[i] == str[j])
            ++j;
        next[i] = j;
    }
    return next[strLength - 1];
}

int main() {
    int cnt = 0;
    scanf("%d", &cnt);
    while(cnt--) {
        char str[maxn];
        scanf("%s", str);
        int strLength = strlen(str);
        int nextLast = getNextLast(str);
        int loop = strLength - nextLast;
        int result = 0;
        if(loop == strLength) result = strLength;
        else if(loop == 1 || !(strLength % loop)) result = 0;
        else result = loop - strLength % loop;
        printf("%d\n", result);
    }
}

E - Period(hdu1358

Problem Description

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as AK , that is A concatenated K times, for some string A. Of course, we also want to know the period K.

Input

The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it.

Output

For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.

Sample Input

3
aaa
12
aabaabaabaab
0 

Sample Output

Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4

Solve

题意是给你一个长度为n的字符串A,然后求该字符串A的所有的其子串重复得到的前缀,并计算前缀的周期是多少。同样利用next数组,由上题可知next数组可以求循环节,这次是求前缀的循环节,遍历next数组即可。

#include <iostream>
#include <string>
#include <vector>

void getNext(std::vector<int> &next, const std::string &str) {
    int strLength = str.size();
    for(int i = 1, j = 0; i < strLength; ++i) {
        while(j && str[i] != str[j])
            j = next[j - 1];
        if(str[i] == str[j])
            ++j;
        next[i] = j;
    }
}

int main() {
    int cnt = 0;
    int testCaseNo = 0;
    while(std::cin >> cnt && cnt) {
        std::string str;
        std::cin >> str;
        std::vector<int> next(cnt, 0);
        getNext(next, str);
        std::cout << "Test case #" << ++testCaseNo << std::endl;
        for(int i = 1; i < cnt; ++i) {
            int loop = i - next[i] + 1;
            int countRepeat = (i + 1) / loop;
            if(!((i + 1) % loop) && countRepeat > 1)
                std::cout << i+1 << " " << countRepeat << std::endl;
        }
        std::cout << std::endl;
    }
}
参与评论 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

企鹅企鹅企

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值