#include <string>
#include <iostream>
#include <vector>
using namespace std;
class kmp {
string& sample;
vector<size_t> prefix;
int last_prefix;
public:
kmp(string& sample) :sample(sample), prefix(sample.length()) {
last_prefix = prefix[0] = 0;
for (size_t i=1; i<sample.length(); i++) {
next(sample[i]);
prefix[i] = last_prefix;
}
reset();
}
bool next(char c) {
while (last_prefix > 0 && sample[last_prefix] != c)
last_prefix = prefix[last_prefix-1];
if (sample[last_prefix] == c)
last_prefix++;
return last_prefix == sample.length();
}
void reset() {
last_prefix = 0;
}
};
int main() {
string sample = "aabaa";
string text = "aabaabaaaabaabaaab";
kmp matcher(sample);
for (size_t i=0; i<text.length(); i++) {
if (matcher.next(text[i])) {
cout << i + 1 - sample.length() << endl;
}
}
}
I2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmNsYXNzIGttcCB7CglzdHJpbmcmIHNhbXBsZTsKCXZlY3RvcjxzaXplX3Q+IHByZWZpeDsKCWludCBsYXN0X3ByZWZpeDsKcHVibGljOgoJa21wKHN0cmluZyYgc2FtcGxlKSA6c2FtcGxlKHNhbXBsZSksIHByZWZpeChzYW1wbGUubGVuZ3RoKCkpIHsKCQlsYXN0X3ByZWZpeCA9IHByZWZpeFswXSA9IDA7CgkJZm9yIChzaXplX3QgaT0xOyBpPHNhbXBsZS5sZW5ndGgoKTsgaSsrKSB7CgkJCW5leHQoc2FtcGxlW2ldKTsKCQkJcHJlZml4W2ldID0gbGFzdF9wcmVmaXg7CgkJfQoJCXJlc2V0KCk7Cgl9CgkKCWJvb2wgbmV4dChjaGFyIGMpIHsKCQl3aGlsZSAobGFzdF9wcmVmaXggPiAwICYmIHNhbXBsZVtsYXN0X3ByZWZpeF0gIT0gYykKCQkJbGFzdF9wcmVmaXggPSBwcmVmaXhbbGFzdF9wcmVmaXgtMV07CgkJCQoJCWlmIChzYW1wbGVbbGFzdF9w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