http://poj.org/problem?id=3579
lower_bound函数
函数功能:
函数lower_bound()在first和last中的
前闭后开区间进行
二分查找,返回大于或等于val的
第一个元素位置。如果所有元素都小于val,则返回
last的位置且last的位置是越界的。
例如,序列a[i]={12,15,17,19,20,22,23,26,29,35,40,51};用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。
调用lower_bound之前必须确定序列为有序序列,否则调用出错。
函数使用格式:
对于数组a[n]来说lower_bound(a, a+n, val) - a;代表的是a[i]中比val小的数的个数。
AC_CODE:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int N,C,a[100010];
bool check(int mid){
int cnt = 0;
for(int i=0; i<N; i++)
cnt += N - (lower_bound(a, a+N, a[i] + mid) - a);
if(cnt > C) return true;
return false;
}
int main(){
// freopen("in.txt", "r", stdin);
while(scanf("%d",&N) != EOF){
for(int i=0; i<N; i++)
scanf("%d",&a[i]);
C = N * (N - 1) / 4;//中位数在差值表中的位置
sort(a, a+N);
int left = 0, right = a[N-1] - a[0];
int ans = 0;
while(left <= right){
int mid = (left + right) >> 1;
if(check(mid)){
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
printf("%d\n",ans);
}
return 0;
}