Cod sursa(job #3242051)

Utilizator RosheRadutu Robert Roshe Data 8 septembrie 2024 12:36:57
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <string.h>

#define MAX 2000000
using namespace std;

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

int *createSubPatterns(string p){
  int *lps = (int*) malloc(p.length() * sizeof(int));
  int i = 1, j = 0;
  while(i < p.length()){
    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);
      getline(in, p);
      getline(in, s);
      int* lps = createSubPatterns(p);
      /*
      for(int i = 0; i<p.length(); i++)
        cout << lps[i] << ", ";
      cout << endl;
      */
      /*
      int j = 0, i = 0;
      int matches = 0;
      while(i < s.length()){
        if(j == p.length()){
          pos[matches++] = i;
          j = lps[j-1];
          if(matches == 1000)
            break;
        }
        if(s[i] == p[j]){j++; i++;}
        else if(j > 0){
          j = lps[j-1];
        }
        else i++;
      }
      out << matches << endl;
      for(int i = 0; i<matches; i++)
        out << pos[i] - p.length() << " ";
     */  
			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;
}