Cod sursa(job #1213147)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 iulie 2014 12:47:19
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <string.h>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN = 2000005;

char a[MAXN], b[MAXN];
vector <int> matches;
int pi[MAXN];
int n, m;

int main() {
    ifstream fin("strmatch.in");
    ofstream fout("strmatch.out");
    fin >> (a + 1);
    fin >> (b + 1);
    n = strlen(a + 1);
    m = strlen(b + 1);
    int k = 0;
    for(int i = 2 ; i <= n ; ++ i) {
        while(k > 0 && a[k + 1] != a[i])
            k = pi[k];
        if(a[k + 1] == a[i])
            ++ k;
        pi[i] = k;
    }
    k = 0;
    for(int i = 1 ; i <= m ; ++ i) {
        while(k > 0 && a[k + 1] != b[i])
            k = pi[k];
        if(a[k + 1] == b[i])
            ++ k;
        if(k == n)
            matches.push_back(i - n);
    }
    fout << matches.size() << '\n';
    for(int i = 0 ; i < min(1000u, matches.size()) ; ++ i)
        fout << matches[i] << ' ';
    return 0;
}