ArushN27's blog

By ArushN27, history, 6 hours ago, In English

101911E - Painting the Fence

When I first got MLE, I suspected it might be because of #define int long long, but even after changing that I still got MLE. I couldn't figure out what was wrong as I was sure that the space was O(n).

When I used std::set instead of std::deque it used only 100MB memory.

std::deque code
std::set code

Can anybody explain why std::deque has such high memory usage?

  • Vote: I like it
  • +12
  • Vote: I do not like it

»
6 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by ArushN27 (previous revision, new revision, compare).

»
5 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

deque isn't stored contiguously in memory

  • »
    »
    4 hours ago, # ^ |
      Vote: I like it +7 Vote: I do not like it

    This doesn't affect memory consumption though, only cache utilization.

»
4 hours ago, # |
  Vote: I like it +4 Vote: I do not like it

Because its retarded. Deque needs like 2 kilos on its own to prepare for a lot of the shenanigans it can maintain (i.e. random access in constant time). All its subderivates also have the same thing (i.e. queue and stack). So try your best not to use them if you have a lot of them instantiated in parallel.

  • »
    »
    4 hours ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    As a fun fact, you can force stacks to use std::vector by initializing them as stack<int,vector<int>>, but I don't know how this affects performance.

»
4 hours ago, # |
  Vote: I like it +8 Vote: I do not like it

I'm sure a quick Google search would get you to quite a few instances of people crying about deque's memory usage, and some SE answers trying to explain why, so I won't attempt to do that.

As a generally helpful replacement for deque, std::list exists. We tend to largely ignore Linked lists in CP, but the STL implementation is fairly good at basic stuff like popping or inserting at both sides. This fortunately covers almost all uses of deque in most problems, and with less funky behaviour in my experience. It doesn't support O(1) random access though, and it doesn't look like you need it either. Your current code ACs with <100MB using lists.

Less useful: For this specific submission, you can also AC by submitting in C++17, or deleting all deques of size 1 from the map.

Also, your Node has memory leaks. You don't delete l and r. Doesn't fix the issue here though.