您的位置:首页 > 其它

kmp算法 in POJ【POJ3461,POJ2752,POJ2406,POJ1961】

2017-08-29 11:19 369 查看


POJ_3461 Oulipo

简单的kmp使用,找出第一个字符串在第二个字符串中出现的次数

#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
int main(void)
{
char mother[10001];
char son[1001];
cin >> mother >> son;
int next[1001] = {-1};
int i=0;
int j=-1;
int len_son = strlen(son);
int len_mother = strlen(mother);
while(i < len_son)
{
if(j==-1 || son[i]==son[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
i=j=0;
int ans=0;
while(i < len_mother)
{
if(j==-1 || mother[i] == son[j])
{
i++;
j++;
}
else
j = next[j];
if(j==len_son)
ans++;
}
cout << ans << endl;
system("pause");
return 0;
}


POJ_2751 Seek the Name, Seek the Fame

依次输出使字符串前缀后缀相同的逻辑位序

#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
const int Max = 4e5+5;//即400005
char str[Max];
int next[Max],ans[Max];
void get_next(char *str)
{
int i=0,j=-1;
next[0] = -1;
int len=strlen(str);
while(i<len)
{
if(j==-1 || str[i]==str[j])
next[++i] = ++j;
else
j = next[j];
}
}

int main(void)
{
while(cin >> str)
{
get_next(str);
int len = strlen(str);
int k = next[len];
int j=0;
while(k>0)
{
j++;
ans[j] = k;
k = next[k];
}
for(int i=j;i>0;i--)
{
cout << ans[i] <<" ";
}
cout << len <<endl;
}
system("pause");
return 0;
}

POJ_2406 Power Strings

求字符串最多是由多少个子串循环组成 ,kmp算法中next数组的使用

/*****************
POJ 2406
求字符串最多是由多少个子串循环组成
kmp算法中next数组的使用
******************/
#include<iostream>
#include<cstring>
using namespace std;

const int Max_Size = 1000005;

int next[Max_Size];

void Get_next(char *s)
{
int l = strlen(s);
int i=0;
int j=-1;
next[0] = -1;
while(i<l)
{
if(j==-1 || s[i]==s[j])
{
next[++i] = ++j;
}
else
j = next[j];
}
}

int main(void)
{
char str[Max_Size];
while(gets(str))
{
if(strcmp(str,".")==0)
break;
Get_next(str);
int ans = 1;
int l = strlen(str);
if(l%(l-next[l]) == 0)
ans = l/(l-next[l]);
/*else
ans = 1;*/
printf("%d\n",ans);
}

system("pause");
return 0;
}

POJ-1961 Period

类似于2406

#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
const int Max_n = 1000005;
int next[Max_n];
void get_next(char *str)
{
int i=0,j=-1;
int len = strlen(str);
next[0] = -1;
while(i<len)
{
if(j==-1 || str[i]==str[j])
next[++i] = ++j;
else
j = next[j];
}
}
int main(void)
{
int n;
char str[Max_n];
cin >> n;
int count = 1;
while(n!=0)
{
cin >> str;
cout << "Test case #" << count << endl;
count ++;
int i=0,j=-1;
int len = strlen(str);
next[0] = -1;
while(i<n)
{
if(j==-1 || str[i]==str[j])
next[++i] = ++j;
else
j = next[j];
}
for(int k=2;k<=n;k++)
{
if(k%(k-next[k])==0 && k/(k-next[k])!=1)
{
cout << k << " " << k/(k-next[k]) << endl;
}
}
cout << endl;
cin >> n;
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp poj 算法