标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11544 Accepted Submission(s): 7421
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 #include <iostream> 6 #include <cmath> 7 #include <queue> 8 #include <map> 9 #include <stack> 10 #include <list> 11 #include <vector> 12 13 using namespace std; 14 15 const int maxn = 1010; 16 int na, nb; 17 char a[maxn]; 18 char b[maxn]; 19 int pre[maxn]; 20 21 //b是模式串,a是目标串 22 void getpre(char *b, int *pre) { 23 int j, k; 24 pre[0] = -1; 25 j = 0; 26 k = -1; 27 while(j < nb) { 28 if(k == -1 || b[j] == b[k]) { 29 j++; 30 k++; 31 pre[j] = k; 32 } 33 else { 34 k = pre[k]; 35 } 36 } 37 } 38 39 int kmp() { 40 int ans = 0; 41 int i = 0; 42 int j = 0; 43 getpre(b, pre); 44 while(i < na) { 45 if(j == -1 || a[i] == b[j]) { 46 i++; 47 j++; 48 } 49 else { 50 j = pre[j]; 51 } 52 if(j == nb) { 53 ans++; 54 } 55 if(i == na) { 56 return ans; 57 } 58 } 59 } 60 61 int main() { 62 // freopen("in", "r", stdin); 63 while(scanf("%s", a) && strcmp(a, "#") != 0) { 64 scanf("%s", b); 65 na = strlen(a); 66 nb = strlen(b); 67 getpre(b, pre); 68 printf("%d\n", kmp()); 69 } 70 }
标签:
原文地址:http://www.cnblogs.com/vincentX/p/4758827.html