Cod sursa(job #3242050)

Utilizator RosheRadutu Robert Roshe Data 8 septembrie 2024 12:18:12
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

#define MAX 2000000
using namespace std;

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

vector<int> createSubPatterns(const string &p) {
    int n = p.length();
    vector<int> lps(n); // Use vector for dynamic memory management
    int i = 1, j = 0;
    
    // Compute the LPS (Longest Prefix Suffix) array
    while (i < n) {
        if (p[i] == p[j]) {
            j++;
            lps[i] = j;
            i++;
        } else {
            if (j > 0) {
                j = lps[j - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}

int main() {
    string p, s;
    vector<int> pos(1001); // Array to store first 1000 matches
    getline(in, p);
    getline(in, s);

    vector<int> lps = createSubPatterns(p);

    int j = 0, i = 0;
    int matches = 0;

    // KMP Search
    while (i < s.length()) {
        if (p[j] == s[i]) {
            j++;
            i++;
        }
        
        if (j == p.length()) {
            // Found a match at index (i - j)
            if (matches < 1000) {
                pos[matches] = i - j;
            }
            matches++;
            j = lps[j - 1]; // Prepare for the next possible match
        } else if (i < s.length() && p[j] != s[i]) {
            // Mismatch after j matches
            if (j != 0) {
                j = lps[j - 1];
            } else {
                i++;
            }
        }
    }

    // Output the results
    out << matches << endl;
    for (int k = 0; k < min(matches, 1000); k++) {
        out << pos[k] << " ";
    }

    return 0;
}