Example:
pku3461(Oulipo), hdu1711(Number Sequence)
The template string starts from 0, and the Next array starts from 1.
The template string starts from 0, and the Next array starts from 1.
#include <iostream> #include <cstring> using namespace std; const int maxn = 1000005; int Next[maxn]; char s[maxn], p[maxn]; int slen, plen; void getNext() { int j, k; j = 0; k = -1; Next[0] = -1; while(j < plen) { if(k == -1 || p[j] == p[k]) { ++j; ++k; Next[j] = k; } else k = Next[k]; } } /* Returns the first occurrence of the pattern string T in the main string S The returned position is 0-based. */ int KMP_Index() { int i = 0, j = 0; getNext(); while(i < slen && j < plen) { if(j == -1 || s[i] == p[j]) { i++; j++; } else j = Next[j]; } if(j == plen) return i - plen; else return -1; } /* Returns the number of times the pattern string appears in the main string S */ int KMP_Count() { int years = 0; int j = 0; if(slen == 1 && plen == 1) { if(s[0] == p[0]) return 1; else return 0; } getNext(); for(int i = 0; i < slen; i++) { while(j > 0 && s[i] != p[j]) { j = Next[j]; } if(s[i] == p[j]) j++; if(j == plen) { years++; j = Next[j]; } } return ans; } intmain() { int t; cin >> t; while(t--) { cin >> s >> p; slen = strlen (s); plen = strlen (p); cout << "The first occurrence of the pattern string T in the main string S is: " << KMP_Index() << endl; cout << "The number of times the pattern string T appears in the main string S is: " << KMP_Count() << endl; } return 0; }