In the recent Div4 contest problem F: My submission1 using map + .find fails on TC 25 (TLE). My submission2 using set + .find fails on TC 33 (TLE). But when I used .count with set it barely passes in C++20 (submission) but gave TLE in C++17 as well as C++23. Why is it so?
I find this phenomenon intriguing as well. My solution 296722764 passed, even though it doesn't seem significantly different from the TLE-ed ones. Btw, I used
contains
instead ofcount
orfind
.set is faster than map because in the implementation of these data structure in Red-black Tree, set uses only key whereas map uses both key and value pair. Both
count
andfind
has same time complexity but when used with set or map,count
is faster as it directly returns true or false as only one key is present, but if used with multisetcount
may be slower thanfind
if count of that particular element is high.Edit: And abt this problem, time complexity also differs by number of time
.end()
iterator is called when usingfind
and comparing it with another iterator whereas when usingcount
,.end()
iterator is not required and compared just as boolean value.Tell me more about what you think the
count()
function does and how it is so much faster thanfind()
(hint: the implementation of count is literallyreturn find(v) == end() ? 0 : 1
)GOING DEEPER
find()
is just implimentation oflower_bound
That's what my doubt is, it makes sense that find would be better in case of multisets or vector
As
count()
is implemented usingfind()
internally, compiler optimizations makecount()
faster in practice.count()
avoids iterator handling and simplifies the check to a boolean result, allowing compilers to optimize it more aggressively.Seems to be a matter of whether you use int or long long as well. As $$$x$$$ isn't that large, using int is enough to pass on C++17 (though still taking a whopping 3.6s). Ever since that Div1+2 problem A incident I've been pretty mindful to these type optimizations
Maybe that's the issue, will keep this in mind in future contests. Thnx :)
In F .. my map solution was giving TLE , but unordered map passed with around 700ms .. (rare to see unordered_map solutions passing)
Same for set as well. unordered set passed whereas set TLEd.