Cod sursa(job #837489)

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

#define CMAX 10000002
#define NMAX 50000
#define LMAX 22


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


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))
            count++;
     }
}

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

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

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