Pagini recente » Cod sursa (job #1869451) | Cod sursa (job #1705821) | Cod sursa (job #985149) | Cod sursa (job #312255) | Cod sursa (job #1022419)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int *pi, *match;
string word, text;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
void compute_pi_function(string word) {
int length = word.size();
pi = new int[length];
pi[0] = -1;
for (int i = 1; i < length; i++){
int q = pi[i-1];
while (q != -1 && word[i] != word[q+1])
q = pi[q];
if (word[i] == word[q+1]){
pi[i] = ++q;
} else {
pi[i] = q;
}
}
}
void solve(){
match = new int[text.size()];
int q = -1, length = word.size();
for (int i = 0; i < text.size(); i++){
while (q != -1 && text[i] != word[q+1])
q = pi[q];
if (text[i] == word[q+1]){
match[i] = ++q;
} else {
match[i] = q;
}
}
for (int i = 0; i < text.size(); i++)
cout << match[i] << " ";
cout << "\n";
}
void print(){
int length = word.size() - 1;
int count = 0;
for (int i = 0; i < text.size(); i++){
if (match[i] == length)
count++;
}
g << count << '\n';
for (int i = 0; i < text.size(); i++){
if (match[i] == length)
g << i - match[i] << " ";
}
}
void read(){
f >> word;
f >> text;
}
int main() {
read();
compute_pi_function(word);
for (int i = 0; i < word.size(); i++){
cout << pi[i] << " ";
}
cout << '\n';
solve();
print();
delete [] match;
delete [] pi;
return 0;
}