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

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

Today, I was trying to solve 626E - Simple Skewness, and I had some troubles implementing a ternary search on integers! I knew how to run a ternary search on doubles, but I didn't know how to do it on integers.

So after getting it accepted, I tried reading accepted codes of other people and I found a nice way to do it. since many of the best coders in codeforces (including tourist and Errichto) didn't use this while solving 626E - Simple Skewness, I think many people don't know about it!

So here it is!

int lo = -1, hi = n;
while (hi - lo > 1){
    int mid = (hi + lo)>>1;
    if (f(mid) > f(mid + 1)) 
         hi = mid;
    else 
         lo = mid; 
}
//lo + 1 is the answer
  • Проголосовать: нравится
  • +82
  • Проголосовать: не нравится

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

kllp had a blog post about it.

There are also some discussions below.

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

Correct me if I am wrong but is using the condition r-l < 3 not good enough for ternary search on integers?

ie

//L and R are the range

while(R-L >= 3){

//implementation

}

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

    of course not! both l + 1 and l + 2 can be the answer in this case.

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

Shouldn't the if condition be f(mid) > f(mid + 1)?

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

    I'm assuming that f[x] increases and then decreases, and we want the maximum value of f[x].

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

      Exactly.

      The way it is now, if the condition f(mid) < f(mid + 1) is fulfilled, you're gonna throw everything in the interval [mid + 1, n] away, since you are setting the higher border as mid; but, the maximum f(i) is in [mid + 1, n] since f(mid + 1) is greater than f(mid).

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

Thank you so much for this!

I used it to solve this problem

It's very useful :)

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

Does it work correctly in case f(mid) == f(mid + 1) ? For example: f = {0, 1, 0, 0, 0}

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

Thanks! I used this trick in 631E - Product Sum and get accepted :)

My code: 16554436

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

How do you run ternary search if f(MID)==f(MID+1) [Or even for that matter what if f((2*LO+HI)/3)==f((LO+2*HI)/3)]??