Cod sursa(job #1736364)

Utilizator DorelBarbuBarbu Dorel DorelBarbu Data 1 august 2016 16:54:18
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

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

const int MAXN = 2000000;

string A, B;
int nA, nB, T[MAXN+1], solSize;
vector <int> sol;

void kmp(string A, string B)
{
    for(int i = 1; i < nA; i++)
    {
        int j = T[i-1];
        while(A[j] != A[i])
        {
            j = T[j-1];
            if(j == 0)
                break;
        }
        if(j == 0 && A[0] == A[i])
            T[i] = 1;
        else
            T[i] = j + 1;
    }
    int i = 0;
    while(i < nB)
    {
        int j = 0;
        while(B[j+i] == A[j] && j < nA && j + i < nB)
            j++;
        if(j == nA)
            sol.push_back(i);
        if(T[j-1] == 0)
            i++;
        else
            i = i + j - T[j-1];
    }
}

int main()
{
    in>>A>>B;
    nA = A.length();
    nB = B.length();
    kmp(A,B);
    out<<sol.size()<<endl;
    solSize = min(1000,(int)sol.size());
    for(int i = 0; i < solSize; i++)
        out<<sol[i]<<' ';
    return 0;
}