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.
题意:给n个数,在C(n,2)个组合数的差值绝对值中找到第k小的 |
思路(二分答案):
·因为是组合数,有无序的性质,所以我们可以先对数组排序,这样方便后续操作,求差值的时候只需要后面减去前面的即可。
·接着二分中位数,拿到一个mid,限制条件怎么设置呢?我们想mid什么时候需要向上移动?不就是比它大的数比组合数的一半多吗?说明这个mid比中位数小,所以我们就要上调mid。反之这说明mid太大,比它小的数不够一半。
·那么就只剩下核心的判断比mid大的数的数量了。因为我们前面已经排好序,而且手上有个mid,所以我们可以对数组的每个位置枚举,看看大于等于mid+a[i]的数有多少个,累加结果和组合数一半判断即可。总体复杂度O(nlognlogn)
AC代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include <queue>
#include<vector>
#define FAST ios::sync_with_stdio(false)
#define abs(a) ((a)>=0?(a):-(a))
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define rep(i,a,n) for(int i=a;i<=n;++i)
#define per(i,n,a) for(int i=n;i>=a;--i)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define maxn 100000+500
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
inline ll read()
{
ll x = 0;
char ch = getchar();
while(ch>'9'||ch<'0') ch = getchar();
while(ch>='0'&&ch<='9') x = (x<<3) + (x<<1) + ch - '0', ch = getchar();
}
ll a[maxn];
ll n,m;
ll cal(ll x)
{
ll cnt = 0;
for(ll i=1;i<=n;i++)
cnt += (a+n+1) - lower_bound(a+i+1,a+1+n,a[i]+x);
return cnt<=m/2;
}
int main()
{
while(~scanf("%lld",&n))
{
for(ll i=1;i<=n;i++)
scanf("%lld",&a[i]);
sort(a+1,a+1+n);
ll L = 1e15, R = -1;
for(ll i=2;i<=n;i++)
L =min(a[i]-a[i-1],L);
R = a[n] ;
m = n*(n-1)/2;
while(L<R-1)
{
ll mid = (L+R)>>1;
if(cal(mid))
R = mid;
else
L = mid;
}
printf("%lld\n",L);
}
return 0;
}