Cod sursa(job #672403)

Utilizator ukiandreaAndreea Lucau ukiandrea Data 1 februarie 2012 23:58:54
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

#include <vector>

#define MAX_STRING_SIZE     2000011

char a[MAX_STRING_SIZE + 1];
char b[MAX_STRING_SIZE + 1];
int t[MAX_STRING_SIZE];

// ----------- BRUTE FORCE -------------
void find_match_hard()
{
    std::vector<int> apps;

    if (strlen(b) < strlen(a)) {
        printf("0\n");
        return;
    }

    for (unsigned int i = 0; i <= (strlen(b) - strlen(a)); i++) {
        if (memcmp(&b[i], a, strlen(a)) == 0) {
            apps.push_back(i);
        }
    }

    printf("%lu\n", apps.size());
    for (std::vector<int>::iterator it = apps.begin(); it != apps.end(); ++it)
        printf("%d ", *it);

    printf("\n");
}
// ----------- END BRUTE FORCE -------------


// ----------- KMP ------------------------
void build_kmp_table()
{
    // t[i] - the amount of backtraking required if there isn't a match
    //      - the length of the longest possible initial segment of W leading up to (but not including) that position
	memset(t, 0, sizeof(t));

    int pos = 2, cnd = 0;

	for (; pos <= strlen(a); pos++) {
		while (a[pos - 1] != a[cnd] && cnd)
			cnd = t[cnd];

		if (a[pos - 1] == a[cnd])
			cnd++;
		t[pos] = cnd;
	}
}

void find_match_kmp()
{
    int n = 0;
    int apps[1000] = {0};

    if (strlen(b) < strlen(a)) {
        printf("0\n");
        return;
    }

    int j = 0, i = 0;

    build_kmp_table();

	for (i = j = 0; i < strlen(b); ) {
        if (b[i] == a[j]) {
			++i, ++j; 
            if (j == (strlen(a))) {
                if (++n < 1000) 
                    apps[n - 1] = i - j;
			}
        } else {
			if (j)
				j = t[j];
			else {
				i++;
			}
        }
    }

    printf("%d\n", n);    
    for (int i = 0; i < (n < 1000 ? n : 1000); i++)
        printf("%d ", apps[i]);

    printf("\n");
}
// ----------- END KMP ------------------------


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

    memset(a, 0, sizeof(a));
    memset(b, 0, sizeof(b));

    scanf("%s\n", a);
    scanf("%s\n", b);

    find_match_kmp();

    return 0;
}