Cod sursa(job #2702547)

Utilizator DragosC1Dragos DragosC1 Data 4 februarie 2021 15:18:17
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
//KMP algorithm
#include <fstream>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

char s1[2000001];
char s2[2000001];
int ns1, ns2;
int table[2000001];
vector<int> ind;
int nr;

void KMP() {
	int i, j;
	i = 0, j = 1;
	while (j < ns1) {
		if (s1[i] == s1[j]) {
			table[j] = i + 1;
			i++, j++;
		}	
		else 
			if (i != 0)
				i = table[i - 1]; 
			else {
				table[j] = 0;
				j++;
			}
	}
	i = 0, j = 0;
	while (i < ns2) {
		if (s2[i] == s1[j])
			i++, j++;
		if (j == ns1) {
			ind.emplace_back(i - j);
			j = table[j - 1];
		}
		if (s2[i] != s1[j]) 
			if (j != 0)
				j = table[j - 1];
			else i++;
	}
}

int main() {
	ios::sync_with_stdio(0);
	int i;
	
	ifstream f("strmatch.in");
	f.getline(s1, 2000001); ns1 = strlen(s1);
	f.getline(s2, 2000001); ns2 = strlen(s2);
	f.close();

	KMP();

	ofstream g("strmatch.out");
	g << ind.size() << '\n';
	if (ind.size() > 1000)
		nr = 1000;
	else nr = ind.size();
	for (i = 0; i < nr; i++)
		g << ind[i] << ' ' ;
	g.close();
	return 0;
}