white_coder's blog

By white_coder, 13 years ago, In English
  • Vote: I like it
  • -8
  • Vote: I do not like it

| Write comment?
»
13 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Replace the pointer array with integer array.

»
13 years ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

Also you can replace integer array with map<char, int>. It probably will help to avoid MLE, but will increase time for accessing to the next trie vertex from O(1) to O(logN), where N is a number of vertex' children.

»
13 years ago, hide # |
 
Vote: I like it +11 Vote: I do not like it

First, you have an unrelated bug: looks like you assume the alphabet has 25 letters instead of 26. Strangely, the solution gets AC anyway. Probably the tests are weak.

Your trie should take about (10^5 characters in dictionary)*(54 pointers in node)*(4 bytes in pointer)=21.6 MB with 32-bit compiler or about twice as much with 64-bit compiler. Since it gets MLE, the OJ probably uses 64-bit compiler. What can you do about it?

1) Instead of allocating the nodes individually with new, preallocate a sufficiently big array of nodes, and instead of 8-byte pointers keep 4-byte indices in this array. code. Replacing pointers with ints is usually not convenient. Though pre-allocating memory like this (and using pointers to it) is usually more convenient and more efficient than using new. Also note the neat one-line "deallocation" of the whole structure.

2) Scrap the trie and just use map<string,int> which, unlike the trie, doesn't take 52 times more memory than necessary. code.