[kuangbin帶你飛]專題十六 KMP & 擴展KMP & Manacher
C - 剪花布條
題目:
Description
一塊花布條,裏面有些圖案,另有一塊直接可用的小飾條,裏面也有一些圖案。對於給定的花布條和小飾條,計算一下能從花布條中儘可能剪出幾塊小飾條來呢?
Input
輸入中含有一些數據,分別是成對出現的花布條和小飾條,其布條都是用可見ASCII字符表示的,可見的ASCII字符有多少個,布條的花紋也有多少種花樣。花紋條和小飾條不會超過1000個字符長。如果遇見#字符,則不再進行工作。
Output
輸出能從花紋布中剪出的最多小飾條個數,如果一塊都沒有,那就老老實實輸出0,每個結果之間應換行。
Sample Input
abcde a3
aaaaaa aa
#
Sample Output
0
3
分析:
對於這種匹配問題(不是與循環節有關的問題)通常都有兩種做法,一種是hash,一種是kmp,
個人比較喜歡用hash,題目中是匹配有多少個一樣的碎花,因爲不能重複比較,故當匹配正確時就應該標記它,或者更直接的更改原來地方的字母讓其無法再匹配即可。
而用kmp匹配的話就需要在匹配成功之後把後面的字母串看成新的主串,然後匹配新串,具體做法就是把已匹配的長度清零即可。
hash AC代碼:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
#include<string>
#include<cstdio>
using namespace std;
#define maxn 1001
string a;
string b;
const int B = 100000007;
typedef unsigned long long ull;
ull _hash(int al, int bl)
{
if (al < bl)return 0;
ull t = 1, ah = 0, bh = 0, cnt = 0;
for (int i = 0; i < bl; i++)t *= B;
for (int i = 0; i < bl; i++)ah = ah*B + a[i];
for (int i = 0; i < bl; i++)bh = bh*B + b[i];
for (int i = 0; i + bl<=al; i++)
{
//cout << a << "\n" << b << endl;
//cout << ah << "\t" << bh << endl;
if (ah == bh)
{
cnt++;
ah = ah - a[i + bl - 1] + '$';
//這是關鍵一步,更改字母之後hash值發生變化,所以變化量爲'$'-a[i+bl-1]
a[i + bl-1] = '$';//更改已匹配的最後一個字母
}
if (i+bl<al)
ah = ah*B - a[i] * t + a[i + bl];
}
return cnt;
}
int main()
{
while (cin>>a&&a!="#")
{
cin >> b;
int al = a.length();
int bl = b.length();
ull res = _hash(al, bl);
cout << res << endl;
}
}
kmp AC代碼:
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<string.h>
using namespace std;
#define maxn 1001
string a;
string b;
int Next[maxn];
void makenext(int bl)
{
Next[0] = 0;
for (int i = 1, j = 0; i < bl; i++)
{
while (j>0 && b[j] != b[i])
j = Next[j - 1];
if (b[i] == b[j])
{
j++;
}
Next[i] = j;
}
}
int kmp(int al, int bl)
{
makenext(bl);
int cnt = 0;
for (int i = 0, j = 0; i < al; i++)
{
while (j>0 && b[j] != a[i])
j = Next[j - 1];
if (b[j] == a[i])
j++;
if (j == bl){
cnt++;
j=0;//相當於重新看待主串和模板串的關係,去掉前面已匹配的主串成爲新串,故清零j
}
}
return cnt;
}
int main()
{
while ((cin >> a)&&(a != "#"))
{
cin >> b;
memset(Next, 0, sizeof(Next));
int al = a.length();
int bl = b.length();
int res = kmp(al, bl);
cout << res << endl;
}
}
這是hash ac的結果
這是kmp ac的結果
兩者在空間似乎是一樣的。