题意: 给N数字, X1, X2, … , XN,我们计算每对数字之间的差值:∣Xi - Xj∣ (1 ≤ i < j ≤ N). 我们能得到 C(N,2) 个差值,现在我们想得到这些差值之间的中位数。
如果一共有m个差值且m是偶数,那么我们规定中位数是第(m/2)小的差值。
( Xi ≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )
思路: 很神奇的一个题
- 总共有 n * (n - 1) / 2个差值,那么比中位数大的就有 n * (n - 1) / 4个数
- 那么就可以二分答案ans,并对ans进行判断
- 找到原序列a中大于等于ans + a[i]的数的个数x,那么那么对应所以得i的x相加得到的cnt若等于 n * (n - 1) / 4的时候就找到答案啦
代码实现:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll mod = 1e9 + 7;
const int N = 1e6 + 5;
int n, sum;
int a[N];
int cheak(int x){
int cnt = 0;
for(int i = 1; i <= n; i ++)
cnt += n - (lower_bound(a + 1, a + n + 1, x + a[i]) - a - 1);
return cnt > sum;
}
signed main()
{
IOS;
while(~scanf("%d", &n)){
for(int i = 1; i <= n; i ++)
scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
int l = 1, r = a[n], mid, ans;
sum = 1LL * n * (n - 1) / 4;
while(l <= r){
mid = l + r >> 1;
if(cheak(mid)) ans = mid, l = mid + 1;
else r = mid - 1;
}
cout << ans << endl;
}
return 0;
}