POJ 3579,poj 3685解题记录
二分中值,检查的时候继续二分,二分套二分。。。。。
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<functional> #include<queue> using namespace std; typedef long long ll; const int maxv=1e5+30; ll n; ll tol; ll a[maxv]; bool check(ll mid){ ll num=0; for(int i=0;i<n;i++){ if(a[i]+mid>a[n-1]) break; ll *p=lower_bound(a+i,a+n,a[i]+mid); num+=n-(p-a); } if(num>(tol/2)) return 1; else return 0; } int main(){ freopen("in","r",stdin); while(cin>>n){ tol=n*(n-1)/2; for(int i=0;i<n;i++) scanf("%lld",&a[i]); sort(a,a+n); ll l=0,r=1e9; while(r-l>1){ ll mid=(r+l)/2; if(check(mid)) l=mid; else r=mid; } if(check(l)) cout<<l<<endl; else cout<<r<<endl; } return 0; }
poj 3685和这个差不多也贴在这里,感觉二分写得还是有问题。。。老是wa
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<functional> #include<queue> using namespace std; typedef long long ll; const int maxv=5e4+30; ll T,N,m; ll cul(const ll &i,const ll &j){ return i*i+(ll)(1e5)*i+j*j-(ll)(1e5)*j+i*j; } bool check(ll &k){ ll num=0;///小于k的数量 for(int j=N;j>=1;j--){ ll r=N+1,l=0; while(r-l>1){ ll mid=(r+l)>>1; if(cul(mid,j)<k) l=mid; else r=mid; } num+=l; } return num<m; } int main(){ //freopen("in","r",stdin); cin>>T; while(T--){ cin>>N>>m; ll l= -100000 * N,r=N * N + 100000 * N + N * N + N * N; while(r-l>1){ ll mid=(r+l)>>1; if(check(mid)) l=mid; else r=mid; } cout<<l<<endl; } return 0; }