标签:
先来模版:
void getNext(int *b,int m) { Next[0]=-1; int i=0,j=-1; while(i<m&&j<m){ if(j==-1||b[i]==b[j]) Next[++i]=++j; else j=Next[j]; } } int kmp(int *a,int *b,int n,int m) { getNext(b,m); int i=0,j=0; while(i<n&&j<m){ if(j==-1||a[i]==b[j]) i++,j++; else j=Next[j]; } if(j==m) return i-m; return -1; }
kmp部分很容易理解,next数组部分有点难,暂时只有强记了。
这段时间就做kmp了,下面是按做题顺序的,随时更新....
C题:
求串s中串t出现的个数,重叠不算。每次找到后继续kmp即可,由于串t不变,所以不用多次求next数组。话说把kmp的参数加上n和m会更方便灵活的处理一些题目。
http://www.cnblogs.com/--560/p/4555324.html
A题:
简单的kmp水题。
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=70325#problem/A
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<set> #include<map> #include<string> #include<math.h> #include<cctype> #define ll long long #define REP(i,a,b) for(int (i)=(a);(i)<=(b);(i)++) #define REPP(i,a,b,t) for(int (i)=(a);(i)<=(b);(i)+=(t)) #define rep(i,a,b) for(int (i)=(a);(i)>=(b);(i)--) #define repp(i,a,b,t) for(int (i)=(a);(i)>=(b);(i)-=(t)) #define PII pair<int,int> #define fst first #define snd second #define MP make_pair #define PB push_back #define RI(x) scanf("%d",&(x)) #define RII(x,y) scanf("%d%d",&(x),&(y)) #define RIII(x,y,z) scanf("%d%d%d",&(x),&(y),&(z)) #define DRI(x) int (x);scanf("%d",&(x)) #define DRII(x,y) int (x),(y);scanf("%d%d",&(x),&(y)) #define DRIII(x,y,z) int (x),(y),(z);scanf("%d%d",&(x),&(y),&(z)) #define RS(x) scanf("%s",s) #define RSS(x,y) scanf("%s%s",x,y) #define DRS(x) char x[maxn];scanf("%s",x) #define DRSS(x,y) char x[maxn],y[maxn];scanf("%s%s",x,y) #define MS0(a) memset((a),0,sizeof((a))) #define MS1(a) memset((a),-1,sizeof((a))) #define MS(a,b) memset((a),(b),sizeof((a))) #define ALL(v) v.begin(),v.end() #define SZ(v) (v).size() using namespace std; const int maxn=1000100; const int INF=(1<<29); const double EPS=0.0000000001; const double Pi=acos(-1.0); int a[maxn],b[maxn]; int n,m; int Next[maxn]; void getNext(int *b,int m) { Next[0]=-1; int i=0,j=-1; while(i<m&&j<m){ if(j==-1||b[i]==b[j]) Next[++i]=++j; else j=Next[j]; } } int kmp(int *a,int *b,int n,int m) { getNext(b,m); int i=0,j=0; while(i<n&&j<m){ if(j==-1||a[i]==b[j]) i++,j++; else j=Next[j]; } if(j==m) return i-m+1; return -1; } int main() { DRI(T); while(T--){ RII(n,m); REP(i,0,n-1) RI(a[i]); REP(i,0,m-1) RI(b[i]); cout<<kmp(a,b,n,m)<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/--560/p/4592217.html