-4

Hi I'm using a Trie implementation to solve this problem, but oin the codeforces' servers I'm getting runtime error, and on my pc and on Ideone is normal. Any Ideas ? http://codeforces.com/contest/4/problem/C https://ideone.com/dvRL3b

#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>


using namespace std;
#define MAXN  ('z'-'a'+2)
#define VALUE(c) ( (c)-'a' )

struct Trie
{
    Trie *m[MAXN];
    int count;
}trie;

int insert(Trie *  t, char * w){
    if(w[0]=='\0'){
        t->count++;
        return t->count;
    }
    if(t->m[VALUE(w[0])] == NULL){
        t->m[VALUE(w[0])] =(Trie *) malloc(sizeof(Trie));
    }
    return insert(t->m[VALUE(w[0])] , w+1);
}   


int main(){

    int t;
    scanf("%d",&t);

    for (int i = 0; i < t; ++i)
    {
        char *w = NULL;
        w = (char *)malloc(sizeof(char));
        scanf("%s",w);
        //printf("%s\n", w);
        int resp = insert(&trie,w); 
        if(resp > 1){
            printf("%s%d\n", w,resp-1);
        }else{
            printf("OK\n");
        }
    }


    return 0;

}
Guthyerrz
  • 27
  • 5
  • The `malloc`ed node is not guaranteed to hold `NULL`s in `m` and `0` in `count`. When you allocate a new node of the trie, do fill it with the zeroes which you expect it to hold. You can use `memset`, for example, `memset (t->m[VALUE(w[0])], 0, sizeof(Trie));`, on the line after `malloc`. – Gassa Jul 13 '14 at 21:28
  • @Gassa Yep, that was the problem too. Thanks. – Guthyerrz Jul 13 '14 at 23:19

1 Answers1

1

This line:

w = (char *)malloc(sizeof(char));

will only allocate one byte of memory.

The requests in this problem are at most 32 characters so try:

w = (char *)malloc(sizeof(char)*33); // include 1 extra byte for zero termination byte

In addition, you should probably use calloc when allocating memory for each new Trie, i.e. change

t->m[VALUE(w[0])] =(Trie *) malloc(sizeof(Trie));

to

t->m[VALUE(w[0])] =(Trie *) calloc(sizeof(Trie),1);

as otherwise the pointers will not be cleared.

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75