Cod sursa(job #3319663)

Utilizator patrickunudoiBeres Patrick Stefan patrickunudoi Data 2 noiembrie 2025 13:40:27
Problema Potrivirea sirurilor Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <stdio.h>
#include <string.h>
#define p 31
#define mod 1000000007
int ans[2000005];
int count = 0;
int min(int a, int b)
{
    if(a > b)
        return b;
    return a;
}

void isSubstring(char* const s, char* const sub)
{
    unsigned long long power = 1;
    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;
        if(i < len_sub - 1)power = (power * p) % mod;
    }
    if(hash == rolling_hash)
        ans[count++] = 0;
    for(size_t i = 1; i <= len_s - len_sub; ++i)
    {
        rolling_hash = (rolling_hash - power * (s[i - 1] + 1) % mod + 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);
    fclose(f);
    
    
    isSubstring(sub, s);
    fprintf(g,"%d\n", count);
    for(size_t i = 0; i < min(count, 1000); ++i)
        fprintf(g,"%d ", ans[i]);
    fclose(g);

}