zeref_dragoneel's blog

By zeref_dragoneel, history, 9 years ago, In English

http://codeforces.com/contest/512/problem/B

solution id : 12300691 and 12300696 http://codeforces.com/submissions/arbit

unordered_map is giving wrong answers while map gives the correct answer.

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Looks like you use fact, that in map all pairs are sorted. It's true for normal map(because it's based on BST), but wrong for unordered_map(because it's based on hash table and keys are sorted not by value, but by hashs)

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    According to the solution, the ordered property is not making any difference.

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Ok, that's my error :(

      Here

      if (it2 == M.end() || it2->second > cost)
      	M[fc] = cost;
      

      You can add element to map. Maybe it can make iterator it1 invalid...

      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        According to what you are saying, map should give wrong answers however it is the other way round.

        • »
          »
          »
          »
          »
          9 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          When you change container there are magic with iterators, so it's better just not to do it :) You can never be sure what you will get

»
9 years ago, # |
Rev. 2   Vote: I like it +20 Vote: I do not like it

std::map and std::unordered_map have different iterator invalidation rules. Basically, any std::unordered_map iterator can be invalidated after any insertion or deletion because of rehashing, and you can't control it. On other hand, std::map iterator is guaranteed to be valid until you erase it explicitly. That's why you got 2 different results.