Cod sursa(job #2901995)

Utilizator Teodor94Teodor Plop Teodor94 Data 15 mai 2022 00:19:06
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <stdio.h>
#include <string.h>

#define MAX_N 2000000

#define BASE1 256
#define BASE2 197

#define NO_MATCHES 1000

char str[MAX_N + 1];
int strLength;

char pattern[MAX_N + 1];
int patternLength;

void eraseNewLine(char str[], int& length) {
  if (str[length - 1] == '\n')
    str[--length] = 0;
}

int main() {
  FILE *fin, *fout;
  fin = fopen("strmatch.in", "r");
  fout = fopen("strmatch.out", "w");

  int i;
  int pHash1, pHash2;
  int hash1, hash2;
  int power1, power2;
  bool patternFound;

  int matches[NO_MATCHES];
  int noMatches;

  fgets(pattern, sizeof(pattern), fin);
  patternLength = strlen(pattern);
  eraseNewLine(pattern, patternLength);

  fgets(str, sizeof(str), fin);
  strLength = strlen(str);
  eraseNewLine(str, strLength);

  pHash1 = pHash2 = 0;
  hash1 = hash2 = 0;
  power1 = power2 = 1;
  for (i = 0; i < patternLength; ++i) {
    pHash1 = (pHash1 * BASE1 + pattern[i]);
    pHash2 = (pHash2 * BASE2 + pattern[i]);

    hash1 = (hash1 * BASE1 + str[i]);
    hash2 = (hash2 * BASE2 + str[i]);

    if (i > 0) {
      power1 = (power1 * BASE1);
      power2 = (power2 * BASE2);
    }
  }

  noMatches = 0;
  i = patternLength;
  while (i <= strLength) {
    patternFound = hash1 == pHash1 && hash2 == pHash2;

    hash1 -= str[i - patternLength] * power1;
    hash2 -= str[i - patternLength] * power2;

    hash1 = (hash1 * BASE1 + str[i]);
    hash2 = (hash2 * BASE2 + str[i]);

    if (patternFound) {
      ++noMatches;
      if (noMatches <= NO_MATCHES)
        matches[noMatches - 1] = i - patternLength;
    }

    ++i;
  }

  fprintf(fout, "%d\n", noMatches);
  noMatches = noMatches > NO_MATCHES ? NO_MATCHES : noMatches;
  for (i = 0; i < noMatches; ++i)
    fprintf(fout, "%d ", matches[i]);

  fclose(fin);
  fclose(fout);
  return 0;
}