基础KMP两道
1. HDU 1711 Number Sequence
代码:

#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; #define N 10007 int a[1000007],b[N],next[N]; int n,m; void getnext() { next[0] = -1; int i = 0,j = -1; while(i<m) { if(j == -1 || b[i] == b[j]) { ++i,++j; if(b[i] != b[j]) next[i] = j; else next[i] = next[j]; } else j = next[j]; } } int kmp() { int i = -1,j = -1; while(i<n && j<m) { if(j == -1 || a[i] == b[j]) i++,j++; else j = next[j]; } if(j == m) return i-j+1; return 0; } int main() { int t,i,res; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<m;i++) scanf("%d",&b[i]); if(n<m) { printf("-1\n"); continue; } getnext(); res = kmp(); if(res) printf("%d\n",res); else printf("-1\n"); } return 0; }
代码2:

#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; #define N 10007 int a[1000007],b[N],next[N]; int n,m; void getnext() { next[0] = -1; int i = 0,j = -1; while(i<m-1) { if(j == -1 || b[i] == b[j]) next[++i] = ++j; else j = next[j]; } } int kmp() { int i = -1,j = -1; while(i<n && j<m) { if(j == -1 || a[i] == b[j]) i++,j++; else j = next[j]; } if(j == m) return i-j+1; return 0; } int main() { int t,i,res; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<m;i++) scanf("%d",&b[i]); if(n<m) { printf("-1\n"); continue; } getnext(); res = kmp(); if(res) printf("%d\n",res); else printf("-1\n"); } return 0; }
2.POJ 3461 Oulipo
代码:

#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; #define N 10007 char a[1000004],b[N]; int next[N]; int n,m,cnt; void getnext() { next[0] = -1; int i = 0,j = -1; while(i<m) { if(j == -1 || b[i] == b[j]) next[++i] = ++j; else j = next[j]; } } void kmp() { int i = -1,j = -1; while(i<n && j<m) { if(j == -1 || a[i] == b[j]) i++,j++; else j = next[j]; if(j == m) { cnt++; j = next[j]; } } } int main() { int t,i; scanf("%d",&t); while(t--) { scanf("%s",b); scanf("%s",a); n = strlen(a); m = strlen(b); getnext(); cnt = 0; kmp(); printf("%d\n",cnt); } return 0; }
作者:whatbeg
出处1:http://whatbeg.com/
出处2:http://www.cnblogs.com/whatbeg/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
更多精彩文章抢先看?详见我的独立博客: whatbeg.com