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

Автор StellarSpecter, история, 22 месяца назад, По-английски

I can't understand why this solution 268341805 is passing but this 268341778 is giving WA on testcase 2, both codes are 99% same.

TLDR: I am writing down the part of my code which I changed so that my code got AC.

Please all the help would be greatly appreciated. Thank you so much in advance.

auto it = upper_bound(v.begin(),v.end(),val);
                        if(it!=v.end()&&it!=v.begin()) {
                            ans=min(ans,min(abs(*(it)-val),abs(*(--it)-val))); // old
                        }
                        else if(it==v.end()) {
                            ans = min(ans,abs(*(--it)-val));  //old
                        }
                        else if(it==v.begin()) {
                            ans=min(ans,abs(*(it) - val));  //old
                        }
auto it = upper_bound(v.begin(),v.end(),val);
                        if(it!=v.end()&&it!=v.begin()) {
                            auto it2 = it; it--;                                   // new
                            ans=min(ans,min(abs(*it2-val),abs(*(it)-val)));
                        }
                        else if(it==v.end()) {
                            it--;
                            ans = min(ans,abs(*(it)-val));                        // new
                        }
                        else if(it==v.begin()) {
                            ans=min(ans,abs(*it - val));                         // new
                        }
  • Проголосовать: нравится
  • +2
  • Проголосовать: не нравится

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

PS: newbies please don't comment non-sensical things here, Only 1400+ are allowed to comment.

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

gholyo could help.

»
22 месяца назад, скрыть # |
Rev. 3  
Проголосовать: нравится +1 Проголосовать: не нравится

ans=min(ans,min(abs(*(it)-val),abs(*(--it)-val)));

For checking minimum, It will calculate both values for the comparison, but you decrement it which will reflect on the first argument too lol

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

if you compare min(a,b) b is evaluated first however in some compilers a can be evaluated as it depend on compiler so when you do min(*it,*(--it)) it first evaluate second one which cause it to go to previous position and now you compare previous position with previous position

here change ans=min(ans,min(abs(*(--it)-val),abs(*(it)-val))); // compiler is not dumbass

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

Ok