Median
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9886 | Accepted: 3457 |
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
一般排序查找,数据太多不好存。差值的中位数就是,差值处于中间位置的数,用二分查找排序在中间的差值数。
upper_bound (star,end,val)表示从star 到end-1中大于val的第一个数的地址。
upper_bound (star,end,val)-star表示从star 到end-1中大于val的第一个的位置。
1.本题可用它求得是(cnt)与a[i]相减差值<=d的有几个a[j]。cnt>=m表示mid左边差值偏多,mid应往左边移r=mid-1否则l=mid+1;return l;
lower_bound (star,end,val)表示从star 到end-1中大于等于val的第一个数的地址。
2.本题用于它求得是(cnt)与a[i]相减差值>=d的有几个a[j]。cnt>=m表示mid右边的差值偏多,mid应往右边移动,l=mid+1否则l=mid-1;return r;
1
#include
#include
#include
#include
#include
#include
2.
Source Code
Problem: 3579 User: zjingqi
Memory: 760K Time: 563MS
Language: G++ Result: Accepted
Source Code
#include
#include
#include
#include
using namespace std;
const int maxn = 1e5+5;
int a[maxn];
int n, m;
bool test(int d){
int cnt = 0;
for(int i=0;id的a[j]有多少个
}
if(cnt > m) return 1;//差值>d的个数对大于m个,d值偏小
else return 0;
}
int main(){
while(scanf("%d",&n)!=EOF){
m = n*(n-1)/4;
for(int i=0;i=lb){
int mid = (lb+ub)>>1;
if(test(mid)) lb = mid+1;
else ub = mid-1;
}
printf("%d\n", ub);
}
return 0;
}