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

Автор arnav2004, история, 4 года назад, По-английски

I was recently solving this question using binary search(https://codeforces.net/problemset/problem/1201/C). I came to know about my mistake as my formula for calculating mid was low+(high-low)/2 but instead when I use low+(high-low+1)/2 I get AC.

My questions is when(and why) do we use low+(high-low+1)/2. I tried to google it and could not find any link which answers my question.

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

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

Auto comment: topic has been updated by arnav2004 (previous revision, new revision, compare).

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +15 Проголосовать: не нравится

In my implementation of binary search:

  • if the property holds for a suffix, and I want to find the leftmost element such that the property holds, I write this:
Code
  • if the property holds for a prefix, and I want to find the rightmost element such that the property holds, I write this (it's symmetric to the other case):
Code
  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Thank you sir. Could you also tell me that why this condition holds true for a suffix and not for a prefix.

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

      Fixed, I swapped the two cases.
      By the way, the reason of WA in your code is while high-low>1: (because you can have low != high at the end of the binary search). You can notice that, if you replace that line with while high-low>0:, you get TLE. This is because the code can get stuck in an infinite loop in cases like low = 2, high = 3, mid = 2, low = mid = 2.
      Hence, you have to put mid = (low + high + 1) / 2 instead of mid = (low + high) / 2.

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

      Also, If you use while(low<=high)

      Then to avoid infinite loop use,

      if(can) low = mid+1;
      else high = mid-1;
      
»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by arnav2004 (previous revision, new revision, compare).