1. 题面:
Description
Given N numbers, X1, X2, … , XN, let us calculate the difference of every pair of numbers: ∣Xi - Xj∣ (1 ≤ i < j ≤ N). We can get C(N,2) differences through this work, and now your task is to find the median of the differences as quickly as you can!
Note in this problem, the median is defined as the (m/2)-th smallest number if m,the amount of the differences, is even. For example, you have to find the third smallest one in the case of m = 6.
Input
The input consists of several test cases.
In each test case, N will be given in the first line. Then N numbers are given, representing X1, X2, … , XN, ( Xi ≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )Output
For each test case, output the median in a separate line.
2. 思路
- 先将a[n]排序
-
x
为中位数 =>
|aj−ai|<x 的个数恰好为一半 => 所有的 aj>ai 中 aj<x+ai 个数为一半
-
x
从 [0,max{|
aj−ai |}] 中二分查找 - 枚举i,在a[n]中利用uppper_bound()二分查找 x+ai<aj(aj>ai) 的个数,若恰为一半,则x为所求
-
x
从 [0,max{|
3. 代码
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int a[100000 + 5];
int n;
int m;
bool uppereq(int k) {
int cnt = 0;
for (int i = 0; i < n; i++) {
int temp = (upper_bound(a, a + n, a[i] + k) - a)-1;
//返回为地址,所以用&a[0]来修正,得到所有符合要求的元素的最大下标
cnt += temp - i;
}
if (cnt >=m) return true;
else return false;
}
int main() {
//while (cin>>n) {
while (scanf("%d", &n) != EOF){
int ans ;
m = ((n*(n-1)>>1) + 1)>>1;
for (int i = 0; i < n; i++)
//cin >> a[i];
scanf("%d", &a[i]);
sort(a, a + n);
int up = a[n - 1] - a[0];
int low = 0;
//for (; low <= up;) {
while(low<=up){
int mid = (low + up) >> 1;
if (uppereq(mid)) { ans = mid; up = mid - 1; }
//uppereq(mid)函数用作一个“大于”信号
else low = mid + 1;
}
//cout << ans << endl;
printf("%d\n", ans);
}
return 0;
}
4. 所得
- 对二分法的理解:
- 范围:适用于有序序列,可为各元素存在的有序数组,如本题a[n],也可为确定的数据范围,如本题[0,a[n-1]-a[0]]
- 条件:需要一个“大于/小于”的信号,如本题中设置的
bool upppereq()
- 赋值:二分法实现时,注意为
l=mid+1
r=mid-1
,缺少“1”则可能导致边界情况跳不出循环
- 实现细节:
cin
输入慢于scanf
, 本题使用cin
则会TLE- 注意奇偶性 / 边界的±1