Cod sursa(job #1290075)

Utilizator tudi98Cozma Tudor tudi98 Data 10 decembrie 2014 19:52:12
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;

vector<int> Sol;

int pi[2000005];
char A[2000005],B[2000005];

void compute_pi(char A[],int n)
{
    pi[1] = 0;
    int k = 0;
    for(int i = 2; i <= n; i++)
    {
        while(k > 0 && A[k+1] != A[i])
            k = pi[k];
        if(A[i] == A[k+1])
            k++;
        pi[i] = k;
    }
}

int main()
{
    freopen("strmatch.in", "r", stdin);
    freopen("strmatch.out", "w", stdout);

    fgets(A+1, sizeof(A), stdin);
    fgets(B+1, sizeof(B), stdin);
    int n = strlen(A+1)-1;
    int m = strlen(B+1)-1;

    if(n > m)
    {
        printf("0");
        return 0;
    }

    compute_pi(A,n);

    int k = 0;
    for(int i = 1; i <= m; i++)
    {
        while(k > 0 && A[k+1] != B[i])
            k = pi[k];
        if(A[k+1] == B[i])
            k++;
        if(k == n)
        {
            Sol.push_back(i-n);
        }
    }

    printf("%d\n",Sol.size());
    int lim = Sol.size();
    if(lim > 1000) lim = 1000;
    for(int i = 0; i < lim; i++)
        printf("%d ",Sol[i]);

}