prb09's blog

By prb09, history, 3 months ago, In English

`can anyone tell why my second code gives tle, while first gets accepted?? Problem link : https://codeforces.net/contest/2004/problem/D

Correct Code
TLE Code
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
3 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

When using a (ordered) map you should do it.lower_bound(x) instead of lower_bound(it.begin(), it.end(), x). The former works in $$$O(log(n))$$$ time and the latter in $$$O(n)$$$.

  • »
    »
    3 months ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    The lower bound is on vector. So why is there any issue?

    • »
      »
      »
      3 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      It's pointer and & problem read how these things work. In few words just don't use them often because they use additional memory and time.

    • »
      »
      »
      3 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      You're right mb.

»
3 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it
// for (auto it : mp) -> full copy
// for (auto& it : mp) 

Here, you have to iterate over reference of the map not make a full copy again.

  • »
    »
    3 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Oh got it thanks!!

    • »
      »
      »
      3 months ago, # ^ |
      Rev. 3   Vote: I like it 0 Vote: I do not like it

      Prakhars_alt Suggestion is correct but the reasoning is half right.

      It can also throw TLE because the Vectors inside the map are not sorted.

      mp["1"] = {5, 4, 3, 2};
          for (auto it: mp)
          {
              sort(it.second.begin(), it.second.end());
          }
      
      // output for mp["1"]
      // 5, 4, 3, 2
      

      So, using the reference, (auto &it : mp), the vector inside the map will get sorted.

      PS: Like there's no use of sorting without reference, if you are going to use the map later.