题目链接: http://poj.org/problem?id=3579
题解: n<=100000, 如果用O(n^2)的方法肯定超时的。所以要用二分搜索的方法。做法是将答案的范围二分,在每一次二分中统计有多少对元素的差值小于等于mid,如果大于等于总对数的一半,则表明当前的mid是比实际大了的或者就是答案,那么就缩小mid。如果小于总对数的一半,则说明当前mid比实际小了,那么要扩大mid。这样步步逼近。最后的就是答案了。
需要注意的是:在找有多少对元素的差值小于mid时,如果用O(n^2)的方法也是会超时的,这里处理的方法是用upper_bound(), 听说这个函数是用二分实现的。
学习:
1.lower_bound(a,a+n,d)-a,返回a[i]<d的个数。
2.upper_bound(a,a+n,d)-a, 返回a[i]<=d的个数。
3.对二分新的理解:二分除了可以直接找到目标,还可以步步逼近目标,当循环结束时,目标便浮出水面。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<string>
#include<set>
#define LL long long
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a<b?a:b)
#define INF 0x7fffffff
#define LNF ((1LL<<62)-1)
#define maxn 200010
using namespace std;
int a[100005];
int n,i,j,m,tmp;
int test(int x)
{
int sum = 0, cnt;
for(int i = 0; i<n; i++)
cnt = upper_bound(a+i+1,a+n,a[i]+x)-(a+i+1), sum += cnt;
if(sum>=tmp) return 1;
return 0;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(i = 0; i<n; i++)
scanf("%d",&a[i]);
m = n*(n-1)/2;
tmp = (m+1)/2;
sort(a,a+n);
int h = 0, t = a[n-1] - a[0];
while(h<=t)
{
int mid = (h+t)/2;
if(test(mid))
t = mid - 1;
else
h = mid + 1;
}
cout<<h<<endl;;
}
}