Cod sursa(job #1118078)

Utilizator breta.ionutBreta Ionut breta.ionut Data 23 februarie 2014 23:27:57
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int *buildPMTable(string w) {
	int *pMTable, wLen = w.length(), i, j;

	pMTable = new int[wLen];
	pMTable[0] = 0;
	for (i = 1 ; i < wLen ; i ++) {
		j = pMTable[i - 1];

		while (j > 0) {
			if (w[j] == w[i]) {
				pMTable[i] = j + 1;
				break;
			}
			j = pMTable[j - 1];
		}

		if (j == 0) {
			pMTable[i] = (w[i] == w[0]) ? 1 : 0;
		}
	}

	return pMTable;
}

int main() {
	ifstream in("strmatch.in");
	ofstream out("strmatch.out");
	string s, w;
	int *pMTable, i, j, wLen, sLen, count;
	vector<int> result;
	vector<int>::iterator it;

	getline(in, w);
	getline(in, s);
	wLen = w.length();
	sLen = s.length();
	pMTable = buildPMTable(w);
	for (i = 0, j = 0 ; i < sLen ; i ++)
		if (s[i] == w[j]) {
			if (j == wLen - 1) {
				result.push_back(i - wLen + 1);
				j = pMTable[j];
			}
			else {
				j ++;
			}
		}
		else {
			j = (j > 0) ? pMTable[j - 1] : 0;
			while (j > 0) {
				if (s[i] == w[j]) {
					j ++;
					break;
				}
				j = (j > 0) ? pMTable[j - 1] : 0;
			}
			if (j == 0 && w[0] == s[i]) j = 1; 
		}

	out<<result.size()<<"\n";
	count = 0;
	for (it = result.begin() ; it != result.end() ; it ++) {
		out<<*it<<" ";
		count++;
		if (count == 1000) break;
	}

	in.close();
	out.close();

	return 0;
}