Pagini recente » Cod sursa (job #1696652) | Cod sursa (job #1545207) | Cod sursa (job #1464882) | Cod sursa (job #1168974) | Cod sursa (job #3319654)
#include <stdio.h>
#include <string.h>
#define p 479
#define mod 1000000007
int ans[2000005];
int count = 0;
unsigned long long int fastExp(unsigned long long int base, unsigned long long int exp)
{
if(exp == 0 || base == 1)
return 1;
if(exp == 1)
return base;
unsigned long long int aux = fastExp(base, exp / 2);
aux = aux * aux % mod;
if(exp % 2)
return aux * base % mod;
return aux % mod;
}
void isSubstring(char* const s, char* const sub)
{
int len_s = strlen(s), len_sub = strlen(sub);
unsigned long long int hash = 0, rolling_hash = 0;
//Calculam hash-ul pentru sub
for(size_t i = 0; i < len_sub; ++i)
{
hash = ((hash * p % mod) + (sub[i] + 1)) % mod;
rolling_hash = ((rolling_hash * p % mod) + (s[i] + 1)) % mod;
}
for(size_t i = 1; i < len_s - len_sub; ++i)
{
rolling_hash = (rolling_hash - fastExp(p, len_sub - 1) * (s[i - 1] + 1) + mod) % mod;
rolling_hash = (rolling_hash * p + (s[i + len_sub - 1] + 1)) % mod;
if(hash == rolling_hash)
ans[count++] = i;
}
}
int main()
{
FILE *f = fopen("strmatch.in", "r");
FILE *g = fopen("strmatch.out", "w");
static char s[2000005];
static char sub[2000005];
fgets(s, 2000005, f);
fgets(sub, 2000005, f);
printf("%s", sub);
fclose(f);
fclose(g);
s[strlen(s) - 1] = '\0';
sub[strlen(sub) - 1] = '\0';
isSubstring(sub, s);
printf("%d\n", count);
for(size_t i = 0; i < count; ++i)
printf("%d ", ans[i]);
}