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

Автор Jexy, история, 14 месяцев назад, По-русски

?

Теги c++, set
  • Проголосовать: нравится
  • -9
  • Проголосовать: не нравится

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

No, you can't. However, if you use ordered set, you can do this in $$$O(log(N))$$$

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

No, it is not possible to calculate std::distance() for iterators in std::set with O(N) complexity. The reason for this is that std::set is implemented as a balanced binary search tree, which means that the elements are stored in a non-contiguous order. As a result, the distance between two iterators in a std::set can only be calculated by traversing the tree from one iterator to the other, which takes O(log n) time complexity, where n is the number of elements in the set. Therefore, std::distance() for iterators in std::set has a worst-case time complexity of O(log n).

  • »
    »
    14 месяцев назад, # ^ |
    Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

    Therefore, std::distance() for iterators in std::set has a worst-case time complexity of O(log n)

    no lol iterator traversal on std::set is $$$O(\text{distance})$$$, so basically this is $$$O(N)$$$

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

You can use __gnu_pbds::tree and set node update to tree_order_statistics_node_update.

After that just call order_of_key to find distance between two elements in $$$O(\log N)$$$ time.

For std::set<Key,Compare,Allocator>::iterator, it is mentioned in https://en.cppreference.com/w/cpp/iterator/distance that its time complexity is linear. Not sure if we could do better as std::set<> is too packaged.

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

it is impossible to get distance or indicies in a set in less than O(N) time, however using the ordered set data structure can do this in O(log N) time.

ordered set implementation

https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds/

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

You can use segment tree is similar to set and O(log(n))