Pagini recente » Cod sursa (job #1865080) | Cod sursa (job #1148736) | Cod sursa (job #1132287) | Cod sursa (job #1998556) | Cod sursa (job #1710743)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
void PrefixFunction(const std::string& str, std::vector<int>& prefix){
int i, j;
j = 0;
prefix[0] = 0;
for (i = 1; i < (int)prefix.size(); i++) {
while (j > 0 && str[j] != str[i]) {
j = prefix[j - 1];
}
if (str[i] == str[j]) {
j++;
}
prefix[i] = j;
}
}
void KMP(const std::string& str, const std::string& word){
int i, j;
int count;
i = 0;
j = 0;
std::vector<int> prefix(str.size());
std::vector<int> matches;
int k;
count = 0;
k = 0;
std::ofstream g("strmatch.out");
PrefixFunction(word, prefix);
while (i < (int)str.size()) {
while(str[i] == word[j] && j < (int)word.size() && i < (int)str.size()){
i++;
j++;
}
if(j == (int)word.size()){
count++;
if(k < 1000) {
k++;
matches.push_back(i-j);
}
j = prefix[j-1];
} else {
if (j > 0){
j = prefix[j - 1];
} else {
i++;
}
}
}
g << count << std::endl;
for(i = 0; i < k; i++){
g << matches[i] << " ";
}
}
int main(){
std::string str;
std::string word;
std::ifstream f("strmatch.in");
std::getline(f,word);
std::getline(f,str);
f.close();
KMP(str, word);
return 0;
}