Cod sursa(job #3319656)

Utilizator patrickunudoiBeres Patrick Stefan patrickunudoi Data 2 noiembrie 2025 13:23:45
Problema Potrivirea sirurilor Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <stdio.h>
#include <string.h>
#define p 479
#define mod 1000000007
int ans[2000005];
int count = 0;
int min(int a, int b)
{
    if(a > b)
        return b;
    return a;
}
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);
    fclose(f);
    
    s[strlen(s) - 1] = '\0'; 
    sub[strlen(sub) - 1] = '\0';
    
    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);

}