Cod sursa(job #837487)

Utilizator szabibibiOrban Szabolcs szabibibi Data 18 decembrie 2012 01:14:00
Problema Abc2 Scor 0
Compilator c Status done
Runda Arhiva de probleme Marime 2.07 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define CMAX 10000000
#define NMAX 50000
#define LMAX 22


char cuv[CMAX];
unsigned long hash[NMAX];
unsigned long threes[20] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683,
                            59049, 177147, 531441, 1594323, 4782969, 14348907,
                            43046721, 129140163, 387420489};


long n, l, c;
long count;

unsigned long val(char *s)
{
    long i;
    unsigned long sol = 0;
    
    for (i = 0; i < l; i++)
        sol += threes[l - i - 1] * (s[i] - 'a');
    return sol;
}

int binsearch(unsigned long val)
{
    long m;
    long s = 0;
    long e = n - 1;
    while (s <= e)
    {
        m = (s + e) / 2;
        if (hash[m] < val)
           s = m + 1;
        else if (hash[m] > val)
           e = m - 1;
        else
            return 1;
    }
    return 0;
}
    

void read()
{
     FILE *f = fopen("abc2.in", "r");
     char s[LMAX];
     fgets(cuv, CMAX, f);
     c = strlen(cuv) - 1;
     cuv[c] = '\0';
     fgets(s, LMAX, f);
     l = strlen(s) - 1;
     s[l] = '\0';
     hash[n++] = val(s);
     while (fgets(s, LMAX, f) != NULL)
     {
           s[l] = '\0';
           hash[n++] = val(s);
     }
     fclose(f);
}

void dostuff()
{
     long i;
     char s[LMAX];
     strncpy(s, cuv, l);
     unsigned long vall = val(s);
     unsigned long sval, eval;
     if (binsearch(vall))
        count++;
     for (i = 1; i <= c - l; i++)
     {
         sval = (cuv[i - 1] - 'a') * threes[l - 1];
         eval = cuv[i + l - 1] - 'a';
         vall = (vall - sval) * 3 + eval;
         if (binsearch(vall))
         {
            printf("%d\n", vall);
            count++;
         }
     }
}

void print()
{
     FILE *f = fopen("abc2.out", "w");
     fprintf(f, "%ld", count);
     fclose(f);
}

int compare (const void * a, const void * b)
{
  return (*(int*)a - *(int*)b);
}

int main()
{
    read();
    qsort(hash, n, sizeof(unsigned long), compare);
    dostuff();
    print();
    return 0;
}