题意:给出一组数据, 计算∣Xi- Xj∣ (1 ≤ i < j ≤ N)., 只要是满足 j > i就可以, 求所有差值的中位数。
解题思路:二分答案, 然后看是不是中位数就可以了, 判断中位数时, 可以线性判断,因为已经排过序了。
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.
Sample Input
4 1 3 2 4 3 1 10 2
Sample Output
1 8
Memory: 836 KB | Time: 141 MS | |
Language: G++ | Result: Accepted |
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<cctype>
#include<list>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
#define FOR(i, s, t) for(int i = (s) ; i <= (t) ; ++i)
#define REP(i, n) for(int i = 0 ; i < (n) ; ++i)
int buf[10];
inline long long read()
{
long long x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
inline void writenum(int i)
{
int p = 0;
if(i == 0) p++;
else while(i)
{
buf[p++] = i % 10;
i /= 10;
}
for(int j = p - 1 ; j >= 0 ; --j) putchar('0' + buf[j]);
}
/**************************************************************/
#define MAX_N 100005
const int INF = 0x3f3f3f3f;
int a[MAX_N];
int n, m;
bool f(int x)
{
int cnt = 0;
int j = 1;
for(int i = 2 ; i <= n ; i++)
{
while(a[i] - a[j] > x)
{
j++;
}
cnt = cnt + i - j;
if(cnt >= m) return true;
}
if(cnt >= m) return true;
else return false;
}
int main()
{
while(~scanf("%d", &n))
{
for(int i = 1 ; i <= n ; i++)
{
a[i] = read();
}
m = n * (n - 1) / 4;
if((n*(n-1)/2)%2) m++;
sort(a + 1, a + n + 1);
int lb = 0, ub = a[n];
while(ub - lb > 1)
{
int mid = (lb + ub) / 2;
if(f(mid)) ub = mid;
else lb = mid;
}
printf("%d\n", ub);
}
return 0;
}