Cod sursa(job #928484)

Utilizator Catah15Catalin Haidau Catah15 Data 26 martie 2013 14:27:30
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

#define NM 2000005
#define PB push_back

int p[NM], N, M;
string S, T;
vector <int> sol;


void compute_prefix()
{
	p[0] = -1;
	p[1] = 0;
	for (int i = 2; i <= N; ++i)
	{
		int x = i-1;
		while (x >= 1 && S[p[x]] != S[i-1]) x = p[x];
		p[i] = p[x] + 1;
	}
}

void apply_kmp()
{
	int x = 0, s = 0;
	while (s + x <= M)
	{
        while (x >= 1 && T[s + x] != S[x]) s = s + x - p[x], x = p[x];

        if (T[s + x] == S[x])
        {
            x ++;

            if (x == N)
            {
                sol.PB (s);
                s = s + x - p[x];
                x = p[x];
            }
        }
        else ++ s;

	}
}

int main()
{
	ifstream f ("strmatch.in");
	ofstream g ("strmatch.out");

	f >> S >> T;
	N = S.length();
	M = T.length();

	compute_prefix();
	//for (int i = 0; i <= N; ++i) cout << i << " -> " << p[i] << endl;
	apply_kmp();

	g << sol.size() << '\n';
	unsigned int constt = 1000;
	for (unsigned int i = 0; i < min (constt, sol.size()); ++ i) g << sol[i] << " ";

	return 0;
}