Cod sursa(job #1229589)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 17 septembrie 2014 19:30:44
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "strmatch.in";
const char outfile[] = "strmatch.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 2000005;
const int oo = 0x3f3f3f3f;
const int  P = 73;
const int  MOD1 = 100007;
const int MOD2 = 10002;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

char A[MAXN], B[MAXN];
int N, M, hashA1, hashA2, P1 = 1, P2 = 1, hashB1, hashB2;
vector <int> matches;

int main() {
    fin >> (A + 1) >> (B + 1);
    N = strlen(A + 1);
    M = strlen(B + 1);

    for(int i = 1 ; i <= N ; ++ i) {
        hashA1 = (hashA1 * P + A[i]) % MOD1;
        hashA2 = (hashA2 * P + A[i]) % MOD2;
        P1 = (P1 * P) % MOD1;
        P2 = (P2 * P) % MOD2;
    }

    if(N > M) {
        fout << "0\n";
        fin.close();
        fout.close();
        return 0;
    }

    for(int i = 1 ; i <= N ; ++ i) {
        hashB1 = (hashB1 * P + B[i]) % MOD1;
        hashB2 = (hashB2 * P + B[i]) % MOD2;
    }
    for(int i = 1 ; i <= M - N + 1 ; ++ i) {
        if(hashA1 == hashB1 && hashA2 == hashB2)
            matches.push_back(i - 1);
        hashB1 = (((((hashB1 * P) % MOD1 - (B[i] * P1) % MOD1 + MOD1) % MOD1) + B[i + N]) % MOD1);
        hashB2 = (((((hashB2 * P) % MOD2 - (B[i] * P2) % MOD2 + MOD2) % MOD2) + B[i + N]) % MOD2);
    }
    fout << matches.size() << '\n';
    for(int i = 0 ; i < min(1000, matches.size()) ; ++ i)
        fout << matches[i] << ' ';
    fin.close();
    fout.close();
    return 0;
}