Strange thing happen in binary search?? PLEASE HELP!!

Правка en1, от rover1, 2019-11-03 15:25:42

Recently i was doing this (https://codeforces.me/contest/448/problem/D) question and got stuck when my solution goes in infinite loop then i see the correct solution and notice the difference and dry run my code, then i realize my code is incorrect. Now i want to know why this happen.. my solution --

include<bits/stdc++.h>

using namespace std;

define LL long long

int main() { LL n,m,k; cin>>n>>m>>k; LL l=1,r=n*m,mid; while(l<r) { mid=(l+r)>>1; LL cnt=0; for (LL i=1;i<=n;i++) cnt+=min(m,(mid-1)/i); if (cnt<k) l=mid; else r=mid; } cout <<l<<endl; return 0; }**** correct solution --

include

include

include

include

include

include

include

include

include

include <memory.h>

using namespace std; typedef long long ll;

const int N = 1e6+6;

ll f(ll x, int n, int m){ ll res = 0; --x; for(int i=1;i<=n;++i) res+=min((ll)m, x/i); return res; }

int main(){ //freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);

int n, m;

cin>>n>>m;

ll k;

cin>>k;


ll l = 1, r = 1LL*n*m+1;

while(l<r){
    ll x = (l+r)>>1;

    if(f(x,n,m)<k) **l = x+1**; else r = x;
}

cout<<l-1<<endl;

return 0;

} Please HELP..

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский rover1 2019-11-03 15:27:46 1062
en1 Английский rover1 2019-11-03 15:25:42 1477 Initial revision (published)