Cod sursa(job #3123173)

Utilizator ridicheTudor Diaconu ridiche Data 22 aprilie 2023 13:05:04
Problema Potrivirea sirurilor Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>

using namespace std;

ifstream in;
ofstream out;

int np, p[1005], T[2000005];

int main()
{
    in.open("strmatch.in");
    out.open("strmatch.out");
    string s, w;
    in >> w >> s;
    int j = 0, k = 0;


    for (int i = 0; i < w.size(); i++)
    {
        T[i] = -1;
        for (int j = 0; j < i; j++)
        {
            //out << i << ":" << j << " " << w.substr(0, j) << ":" << w.substr(i-j, j) << "\n";
            if (w[j] != w[i] && w.substr(0, j) == w.substr(i-j, j))
            {
                T[i] = j;
            }
        }
    }

    for (int j = 0; j < w.size(); j++)
    {
        if (w.substr(0, j) == w.substr(w.size()-j, j))
        {
            T[w.size()] = j;
        }
    }


    np = 0;

    while(j < s.size())
    {
        if(w[k] == s[j])
        {
            j = j + 1;
            k = k + 1;
            if (k == w.size())
            {
                //(occurrence found, if only first occurrence is needed, m becomes j - k  may be returned here)
                if (np < 1000)
                    p[np] = j - k;
                np = np + 1;
                k = T[k]; //(T[length(W)] can't be -1)
            }

        }
        else
        {
            k = T[k];
            if (k < 0)
            {
                j = j + 1;
                k = k + 1;
            }
        }
    }


    out << np << "\n";
    for (int i = 0; i < np && i < 1000; i++)
    {
        out << p[i] << " ";
    }
    return 0;
}