//4_6_2: Oulipo计算单词在文本中出现的次数 POJ3461
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxt = 1000000 + 10;
const int maxw = 10000 + 10;
int cnt;
int nextval[maxw];
void KMP(char str[],char tar[])
{
int i,j,k,str_length,tar_length;
str_length = strlen(str);
tar_length = strlen(tar);
j = 0;
k = -1;
nextval[0] = -1;
while(j < tar_length) //这里的next数组一定要到tar_length,因为不止匹配一次
{
if(k == -1 || tar[j] == tar[k])
{
j ++;
k ++;
if(tar[j] != tar[k])
nextval[j] = k;
else
nextval[j] = nextval[k];
}
else k = nextval[k];
}
/********************上面求出了next数组********************/
i = 0;
j = 0;
while(str[i])
{
if(j == -1 || str[i] == tar[j])
{
i ++;
j ++;
}
else
j = nextval[j];
if(j == tar_length)
{
j = nextval[j]; //nextval数组一定要到tar_length这里
cnt ++;
}
}
}
int main()
{
int loop;
char word[maxw];
char text[maxt];
cin >> loop;
while(loop --)
{
cnt = 0;
cin >> word;
cin >> text;
KMP(text,word);
cout << cnt << endl;
}
return 0;
}
/*测试结果:通过POJ3461检测
3
BAPC
BAPC
1
AZA
AZAZAZA
3
VERDI
AVERDXIVYERDIAN
0
请按任意键继续. . .
*/
POJ3461 Oulipo
最新推荐文章于 2019-08-09 10:46:38 发布