Блог пользователя Jame___boy

Автор Jame___boy, 11 месяцев назад, По-английски

set

For random access iterators, std::distance is O(1). Unfortunately set iterator does not support random access, so the std::distance algorithm has to iterate over the pointers to compute distance, and worst case is O(n).
Example: https://codeforces.net/contest/1915/submission/239386119 (Time limit exceeded)

You can achieve O(log(n)) distance complexity in sets if you use Policy Based Data Structures(PBDS).
Example: https://codeforces.net/contest/1915/submission/239436173 (Accepted)

vector

For std::vector the complexity is O(1) since the iterators support random access. You can also use subtraction operator with the same effect.
Example : (int) (lower_bound(vec.begin(),vec.end(),x) — v.begin()) returns distance from begin to first element in array with value >= x, so it's the same as std::distance(vec.begin(), lower_bound(vec.begin(),vec.end(),x));

Some useful links:

  1. https://youtu.be/MiBrJTNOEP0?si=12Op-IbK7lfqdIbp (বাংলা ভিডিও টিউটোরিয়াল)
  2. https://codeforces.net/blog/entry/45902 (Time complexity of std::distance)
  3. https://stackoverflow.com/questions/13505562/getting-index-of-set-element-via-iterator/13505578
  4. https://codeforces.net/blog/entry/5631?#comment-239276 (How to access to i*th element of a set in c++ effectively (*O(1) or (logN))?)
  5. https://codeforces.net/blog/entry/11080 (C++ STL: Policy based data structures)
  6. https://codeforces.net/blog/entry/11080?#comment-533322 (drawback of using less_equal)

PBDS Code:

  1. https://codeforces.net/contest/1915/submission/239310664
  2. https://codeforces.net/contest/1915/submission/239442547
  • Проголосовать: нравится
  • -8
  • Проголосовать: не нравится

»
11 месяцев назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

Thanks for share this useful resources. I solved last contests F using brute force that's why it take 4.5s :( I will try this PBDS next time

»
11 месяцев назад, # |
  Проголосовать: нравится +11 Проголосовать: не нравится

I think it is O(logn) in the second case... Correct me if I am wrong...

»
10 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

This is what exactly happened to me in 918 Div. 4 as you showed here. I could not fix at the time but I guess it is very helpful for beginners to know this concept.