hdu 1711
hdu 1711
kmp模板题:
#include<stdio.h>
#include<string.h>
#define N 1000005
int s[N];
int p[N];
int next[N];
int m,n;
void getnext(){
int j=0,k=-1;
next[0]=-1;
while(j<m){
if(k==-1||p[j]==p[k]){
j++;
k++;
next[j]=k;
}
else
k=next[k];
}
}
int kmp(){
int i=0,j=0;
getnext();
while(i<n){
if(j==-1||s[i]==p[j]){
i++;
j++;
}
else
j=next[j];
if(j==m)
return i;
}
return -1;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%d",&s[i]);
for(int i=0;i<m;i++)
scanf("%d",&p[i]);
if(kmp()==-1)
printf("-1\n");
else
printf("%d\n",kmp()-m+1);
}
return 0;
}
hdu 3746
hdu3746
利用kmp算法的next数组求最小循环节长度,最小循环节长度等于:cir_len=len-next[len]
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
#define MAX_ 100010
using namespace std;
char patten[MAX_];
int next_[MAX_];
int lenp;
void getnext()
{
int j=0,k=-1;
next_[0]=-1;
while(j<lenp)
{
if(k==-1||patten[j]==patten[k])
{
j++;
k++;
next_[j]=k;
}
else
k=next_[k];
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",patten);
lenp=strlen(patten);
getnext();
int cir=lenp-next_[lenp];
int ans;
if(cir!=lenp&&lenp%cir==0)
ans=0;
else
ans=cir-lenp%cir;
printf("%d\n",ans);
}
return 0;
}
来源:https://blog.csdn.net/weixin_43886143/article/details/100769730