Cod sursa(job #2370771)

Utilizator danhHarangus Dan danh Data 6 martie 2019 13:38:14
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda pregatire_cls12_oji Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <cstring>
#define MAX 2000001
using namespace std;

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

char txt[MAX], pat[MAX];
int lps[MAX];

int nrAp;

void LPS()
{
    int m = strlen(pat);
    int i = 1, len = 0;

    lps[0] = 0;

    while(i < m)
    {
        if(pat[i] == pat[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if(len != 0)
            {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}

void KMP()
{
    int N = strlen(txt), M = strlen(pat);

    LPS();

    int i, j;
    i = j = 0;

    while(i < N)
    {
        if(txt[i] == pat[j])
        {
            i++;
            j++;
        }
        if(j == M)
        {
            nrAp++;
            if(nrAp <= 1000)
            {
                fout<<i - M<<' ';
            }
            j = lps[j-1];
        }
        else if(i < N && txt[i] != pat[j])
        {
            if(j != 0)
            {
                j = lps[j-1];
            }
            else
            {
                i++;
            }
        }

    }
}

int main()
{
    fin.getline(pat, MAX);
    fin.getline(txt, MAX);

    fout<<"              \n";
    KMP();
    fout.close();
    fout.open("strmatch.out", ios::in|ios::out);
    fout<<nrAp;

}