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

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

Today, I was trying to solve 626E - Простая асимметрия, 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 - Простая асимметрия, 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
  • Проголосовать: не нравится

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

kllp had a blog post about it.

There are also some discussions below.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 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

}

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

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

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

Thank you so much for this!

I used it to solve this problem

It's very useful :)

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

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

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

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

My code: 16554436

»
9 лет назад, скрыть # |
 
Проголосовать: нравится -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)]??