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

Автор Nathan_McKane, 5 лет назад, По-английски

I was trying a problem in which I wanted to delete some elements from the set while iterating over the elements of the set.

Link to the problem: Problem C, Educational Round #108

Pseudo Code

for(condition in list_of_conditions):
   for(element X in set):
      if(condition(X) is false):
         remove X from the set
      else:
         answer += result(X)

However, I failed to implement this in an optimized way. I wonder what are some of the shortest and most optimized codes to implement this idea...

Please share your ideas. Thank you!

Failed implementation (Runtime error)

My failed implementation

Accepted implementation

My accepted implementation
  • Проголосовать: нравится
  • +14
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
 
Проголосовать: нравится +6 Проголосовать: не нравится

Instead of making set2, you can make a vector v. Implementation would be similar but time complexity would be lower. Something like this:

Implementation
»
5 лет назад, скрыть # |
Rev. 3  
Проголосовать: нравится +26 Проголосовать: не нравится
for (auto it = s.begin(); it != s.end(); ) {
    if (!condition(*it)) {
        it = s.erase(it);
    } else {
        ++it;
    }
}

Method erase(iterator) for all containers returns iterator to next item after last deleted item, so it works.

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

Use linked list.
Do two vector: a,b
a[i] — Index of first not deleted element after i
b[i] — Index of last not deleted element before i
So, when you delete element at index i do b[a[i]] = b[i]. a[b[i]] = a[i]