Cod sursa(job #2213316)

Utilizator Alex03Runcan Alexandru Alex03 Data 16 iunie 2018 10:56:16
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
/*KMP algorithm has 2 steps first is to make a pattern array for prefix and suffix
and second step is to do the properly search in the text*/

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

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

string text,pattern;
int patternVector[2000000], positions[1001],index;

void VectorMaking () /*There I made a vector where I put the indexes for the KMP algorithm*/
{
    int i;
    index = 0;
    for (i = 1; i <= pattern.length() - 1; )
    {
        if (pattern[i] == pattern[index]) /*If the letters are the same the comparing can start from index value + 1*/
        {
            patternVector[i] = index + 1;
            index++;
            i++;
        } else if (index != 0) index = patternVector[index-1]; /*else we'll search form the patternVector[index-1] value*/
        else
        {
            patternVector [i] = 0; /*or else patternVector[i] will take the 0 value*/
            i++;
        }
    }
}

void KMP()
{
    int i = 0, j = 0; index = 0;
    while (i <= text.length() - 1 && index < 1000) /* there is a while with 2 conditions first for not exit from the text size and second for positions limit of 1000*/
    {
        if (text[i] == pattern[j])
        {
            i++;
            j++;
        } else if (j != 0) j = patternVector[j-1];
        else i++;
        if ( j == pattern.length())
        {
            positions[index + 1] = i - j;
            index++;
            j = patternVector[j - 1];
        }
    }
}

int main ()
{
    getline (fin , pattern);
    getline (fin , text);
    VectorMaking();
    KMP();
    fout << index<< endl;
    for (int i = 1; i <= index ; i++)
        fout << positions[i] << ' ';
    return 0;
}