Cod sursa(job #878140)

Utilizator IronWingVlad Paunescu IronWing Data 14 februarie 2013 02:10:20
Problema Potrivirea sirurilor Scor 18
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdio>
#include <cstring>
#include <assert.h>

# define NMAX 2000001

void computePrefixFunction(char *a, int  *pi, int m){

    pi[0] = 0;
    int k  = 0;

    for(int q = 1; q < m; ++q){
        while (k > 0 && a[k] != a[q]){
            k = pi[k];
        }
        if (a[k] == a[q]){
            ++k;
        }
        pi[q] = k;
    }
}

int pi[NMAX];
char a[NMAX], b[NMAX];
int matches[1024];

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

    fgets(a, NMAX, stdin);
    fgets(b, NMAX, stdin);

    // search a substring into b

    m = strlen(a) - 1; // get rid of newline
    n = strlen(b) - 1; // get rid of \n
    computePrefixFunction(a, pi, m);

    // kmp
    int matchCount = 0;
    int q = 0; // number of characters matched
    for(int i = 0; i < n; i++){
        while ( q > 0 && a[q] != b[i]){
            // next character does not match
            q =  pi[q];
        }
        if (a[q] == b[i])
            ++q;
        if (q == m){
            q = pi[q]; // look for next match
            if(matchCount < 1000)
                matches[matchCount++] = i - m + 1;
        }
    }

    // print matches
    assert(matchCount<=1000);
    printf("%d\n", matchCount);
    for(int i = 0; i < matchCount; ++i){
        printf("%d ", matches[i]);
    }
    putchar('\n');

    return 0;
}