Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

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

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

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

Correct Code
TLE Code
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

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

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)$$$.

  • »
    »
    5 недель назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится

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

    • »
      »
      »
      5 недель назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      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.

    • »
      »
      »
      5 недель назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      You're right mb.

»
5 недель назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится
// 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.

  • »
    »
    5 недель назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Oh got it thanks!!

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

      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.