Pagini recente » Cod sursa (job #990634) | Cod sursa (job #2946726) | Cod sursa (job #1034422) | Cod sursa (job #1311842) | Cod sursa (job #2770106)
#include <stdio.h>
#define MAX_N 2000000
#define MOD1 100007
#define MOD2 100021
#define SIGMA 256
int text[MAX_N], pat[MAX_N], sol[MAX_N];
int main() {
FILE *fin, *fout;
char ch;
int n, m, nrSol, hashPat1, hashPat2, hashText1, hashText2, p1, p2, i;
fin = fopen( "strmatch.in", "r" );
ch = fgetc( fin );
m = 0;
while ( ch != '\n' ) {
pat[m] = ch;
m++;
ch = fgetc( fin );
}
ch = fgetc( fin );
n = 0;
while ( ch != '\n' ) {
text[n] = ch;
n++;
ch = fgetc( fin );
}
p1 = p2 = 1;
hashPat1 = hashPat2 = 0;
for ( i = 0; i < m; i++ ) {
hashPat1 = (hashPat1 * SIGMA + pat[i]) % MOD1;
hashPat2 = (hashPat2 * SIGMA + pat[i]) % MOD2;
if ( i > 0 ) {
p1 = (p1 * SIGMA) % MOD1;
p2 = (p2 * SIGMA) % MOD2;
}
}
hashText1 = hashText2 = 0;
for ( i = 0; i < m; i++ ) {
hashText1 = (hashText1 * SIGMA + text[i]) % MOD1;
hashText2 = (hashText2 * SIGMA + text[i]) % MOD2;
}
nrSol = 0;
if ( hashPat1 == hashText1 && hashPat2 == hashText2 ) {
sol[nrSol] = 0;
nrSol++;
}
for ( i = m; i < n; i++ ) {
hashText1 = (hashText1 - (text[i - m] * p1) % MOD1 + MOD1) % MOD1;
hashText1 = (hashText1 * SIGMA + text[i]) % MOD1;
hashText2 = (hashText2 - (text[i - m] * p2) % MOD2 + MOD2) % MOD2;
hashText2 = (hashText2 * SIGMA + text[i]) % MOD2;
if ( hashPat1 == hashText1 && hashPat2 == hashText2 ) {
sol[nrSol] = i - m + 1;
nrSol++;
}
}
fout = fopen( "strmatch.out", "w" );
fprintf( fout, "%d\n", nrSol );
for ( i = 0; i < nrSol; i++ )
fprintf( fout, "%d ", sol[i] );
fclose( fout );
return 0;
}