# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
Name |
---|
Problem:https://mirror.codeforces.com/contest/1287/problem/B
hg333, problem in memory allocations on heap. Easy fix with runtime
1075ms
.dmkz, that works. But the time complexity O(n*n*k) should not be affected by such things, still they can cause a TLE.
hg333, you have $$$n^2\cdot \log(k)$$$ queries to heap manager. Of course, this is TLE, heap manager works very slow and total runtime of these queries greater than 2 seconds. Try to read how heap manager works.
I understand that changing function argument from :
f ( string s ) to f ( string &s ) makes difference.
Is there something beneficial to even add "const" before it and writing f ( const string &s ) with respect to execution time ?
It guarantees that you are not allowed to change arguments in function body, but it is not significant improvement for runtime, only
0.3s
.Main part is
static string a; a.clear();
: decreases runtime by1.7s
.Are you sure the OP's original code allocated objects on the heap? His string variable is declared with automatic storage duration (i.e. local variable with no new keyword). I think it is allocated on the stack.
std::string class has a pointer to allocated on the heap memory, if string isn't small
Where’s the source of this? I would like to read more.
I think this is just common knowledge, probably mentioned in good C++ books. C++ objects have compile-time constant sizes, so
std::string
must store longer strings separately on the heap.This is example. When we tried to add char 'p', operator new was called for the first time. And yes, looks like for original problem not $$$n^2 \cdot \log(k)$$$ calls, but only $$$n^2$$$ queries to heap manager.
It can be found in source code of C++ STL, I think.
I read through the STL docs. I think the same can be said for any STL container such as vector, set, list, etc. They all have pointers to their underlying elements (whose space is dynamically allocated by an allocator).
So I guess the lesson here is, for a function that has many local variables which are STL containers and is called many times, always put a static storage specifier in front of those variables?
For competitive programming there is a two another solutions: 1) create own memory buffer and rewrite operator new/delete: solution, 1169 ms; 2) use C++17 monotonic buffer resourse (memory pool), when it will be supported by codeforces. Because your program will end by 2-3 seconds and you can ignore memory releases.