题目: 模板题。 ( https://www.luogu.org/problemnew/show/P3375 )
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #define LL long long #define ULL unsigned long long #define rep(i,j,k) for(int i=j;i<=k;i++) #define dep(i,j,k) for(int i=k;i>=j;i--) #define INF 0x3f3f3f3f #define mem(i,j) memset(i,j,sizeof(i)) #define make(i,j) make_pair(i,j) #define pb push_back using namespace std; const int N = 1e6 + 5; int pre[N]; string a, b; int main() { cin >> a >> b; int j = -1; pre[0] = pre[1] = -1; rep(i, 1, (int)b.size() - 1) { while( j > -1 && b[i] != b[j + 1]) j = pre[j]; if(b[j + 1] == b[i]) j++; pre[i] = j; } rep(i, 0, (int)a.size() - 1) { while( j != -1 && b[j + 1] != a[i]) j = pre[j]; if(a[i] == b[j + 1]) j++; if( j == (int)b.size() - 1) { cout << i - b.size() + 2 <<endl; j = pre[j]; } } rep(i, 0, (int)b.size() - 1) { cout << pre[i] + 1 << " "; } return 0; }