Cod sursa(job #580820)

Utilizator varuvasiTofan Vasile varuvasi Data 13 aprilie 2011 15:47:59
Problema Potrivirea sirurilor Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <stdio.h>
#include <string.h>
#define maxn 2000022

char A[maxn], B[maxn];
int pi[maxn], pos[1033];
int matches;

void match()
{
    int lena = strlen(A), lenb = strlen(B);
    int i = 0, j = 0;
    for (i = 0; i <= lenb - lena; i++)
    {
        j = 0;
        while (j < lena && A[j] == B[i+j])
            j++;
        if (j == lena)
            if (matches > 1000)
                matches++;
            else
                pos[matches++] = i;
    }
}

void match_kmp()
{
    int lena = strlen(A), lenb = strlen(B);
    int i = 0, j = 0, k = 0;
    for (i = 0; i < lenb; i++)
    {
        while (k > 0 && A[k] != B[i])
            k = pi[k];
        if (A[k] == B[i])
            k = k + 1;
        pi[i] = k - 1;
        if (k == lena)
            if (matches >= 1000)
                matches++;
            else
                pos[matches++] = i - lena + 1;
                
    }
}

int main()
{
    FILE *fin = fopen("strmatch.in", "rt");
    FILE *fout = fopen("strmatch.out", "wt");
    int i = 0;

    fscanf(fin, "%s\n%s", A, B);
    match_kmp();
    fprintf(fout, "%d\n", matches);
    for (i = 0; i < ((matches > 1000) ? 1000 : matches); i++)
        fprintf(fout, "%d ", pos[i]);

    fclose(fin), fclose(fout);

    return 0;
}