Cod sursa(job #185850)

Utilizator tvladTataranu Vlad tvlad Data 26 aprilie 2008 11:35:42
Problema Potrivirea sirurilor Scor 18
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
#include <string>
#include <vector>
using namespace std;

ifstream fin("strmatch.in");
ofstream fout("strmatch.out");

void prefix ( const string &a, vector<int> &pi ) {
	pi.resize(a.size());
	pi[0] = 0;
	int i, k;
	for (i = 1, k = 0; i < a.size(); ++i) {
		for (; a[i] != a[k+1] && k > 0; k = pi[k]);
		if (k == 0) {
			pi[i] = (a[i] == a[0]) ? 1 : 0;
		} else {
			pi[i] = k+1;
		}
	}
}

void search ( const string &what, const string &where, vector<int> &ret ) {
	vector<int> pi;
	prefix(what,pi);
	for (int i = 0, k = 0; i < where.size(); ++i) {
		for (; where[i] != what[k] && k > 0; k = pi[k]);
		if (where[i] == what[k]) {
			++k;
			if (k == what.size()) {
				ret.push_back(i-what.size()+1);
				k = pi[k-1];
			}
		}
	}
}

int main() {
	string a,b;
	fin >> a >> b;
	vector<int> ap;
	search(a,b,ap);
	fout << ap.size() << "\n";
	for (int i = 0; i < ap.size() && i < 1000; ++i) fout << ap[i] << " ";
	fout << "\n";
	return 0;
}