Cod sursa(job #517008)

Utilizator andreitheo87Teodorescu Andrei-Marius andreitheo87 Data 27 decembrie 2010 15:41:44
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void calc_prefix(string a, vector<int> &prefix) {
	int i, pos = 0;
	prefix[1] = 0;
	for (i = 2; i <= a.size(); ++i)
	{
		while (pos > 0 && a[pos] != a[i-1])
			pos = prefix[pos];
		if (a[pos] == a[i-1])
			++pos;
		prefix[i] = pos;
	}
}
void find_matches(string a, string b, vector <int> prefix, vector<int>& matches) {
	int pos = 0;
	for (int i = 1; i <= b.size(); ++i)
	{
		while (pos > 0 && a[pos] != b[i-1])
			pos = prefix[pos];
		if (a[pos] == b[i-1])
			++pos;
		if (pos == a.size())
		{
			pos = prefix[a.size()];
			matches.push_back(i - a.size() + 1);
		}
	} 
}

int main() {
	ifstream fin("strmatch.in");
	ofstream fout("strmatch.out");
	string a, b;
	fin >> a;
	fin >> b;
	if (a.size() > b.size()) {
		fout << 0 << endl;
		fout.close();
		return 0;
	}
	vector<int> prefix(a.size() + 1);
	calc_prefix(a, prefix);
	vector<int> matches;
	find_matches(a, b, prefix, matches);
	fout << matches.size() << endl;
	for (int i = 0; i < matches.size(); i++) {
		if (i < 1000)
			fout << matches[i] << " ";
	}
	fout << endl;
	for (int i=0; i<b.size()-a.size()+1; i++) {
		bool ok = true;
		for (int j=0; j<a.size(); j++)
			if (a[j] != b[i+j]) ok = false;
		if (ok) fout << i + 1 << " ";
	}
	fout << endl;
	fout.close();
	return 0;
}