Seeking Guidance: Binary Search Quandary on Codeforces

Правка en1, от aryan_singhal, 2024-02-05 21:53:57

Hello fellow developers! I'm relatively new to programming and currently navigating the challenging terrain of Codeforces. I've encountered a perplexing situation while implementing a binary search-based solution for a problem. Despite having a seemingly correct logic, one implementation gets accepted, while the other faces rejection.

I've distilled the issue to a pair of code snippets that encapsulate the identical logic but differ in syntax. Both attempts are centered around a binary search strategy, aiming to crack the problem at hand.

Problem statement: 689C - Mike and Chocolate Thieves

Rejected submission: 244815151 Accepted submission: 244814697

Snippet Comparison: For clarity, I've condensed the snippets to highlight the differences. Your keen eyes might spot the elusive bug that's eluding my scrutiny.

Rejected Code

bool isPos(ll mid, ll m){
    ll ways = 0;
    for(ll k = 2; k * k * k <= mid; k++){
        ways += (mid/(k*k*k));
    }
 
    if(ways >= m){
        return true;
    }else{
        return false;
    }
}
void build(){
    ll m;cin >> m;
 
    ll low = 1;ll high = 1e18;
 
    ll ans = -1;
    while(low <= high){
        ll mid = low + (high - low)/2;
        if(isPos(mid, m)){
            ans = mid;
            high = mid - 1;
        }else{
            low = mid + 1;
        }
    }
 
    if(!isPos(ans, m)){
        cout << -1 << endl;
        return;
    }
 
    cout << ans << endl;
 
}

Accepted Code

ll isPos(ll mid, ll m){
    ll ways = 0;
    for(ll k = 2; k * k * k <= mid; k++){
        ways += (mid/(k*k*k));
    }
 
    return ways;
}
void build(){
    ll m;cin >> m;
 
    ll low = 1;ll high = 1e18;
 
    ll ans = -1;
    while(low <= high){
        ll mid = low + (high - low)/2;
        if(isPos(mid, m) >= m){
            ans = mid;
            high = mid - 1;
        }else{
            low = mid + 1;
        }
    }
 
    if(isPos(ans, m) != m){
        cout << -1 << endl;
        return;
    }
 
    cout << ans << endl;
 
}

Now, as I'm still in the learning phase, I'm reaching out to the experienced members of our programming community for guidance. Could there be some crucial nuances in binary search that I might be overlooking? Or is there a subtle error in my code that's slipping through the cracks?

Happy coding!

Теги binary search, need help

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский aryan_singhal 2024-02-05 21:53:57 2482 Initial revision (published)