Median
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7687 | Accepted: 2637 |
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
Source
题意:
有n个数,每两个数差的绝对值组成一个新的数列,求此数列的中位数偶数时求第m/2小的数
代码:
//两重二分,先将a数组从小到大排序,第一重二分中位数的值m,第二重枚举a[i],找到有多少 //个 |a[j]-a[i]| >= m,将这个数量与n*(n-1)/4比较作为二分的判断条件 #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; const int maxn=100009; int n,a[maxn]; ll k; bool solve(int m){ ll cnt=0; for(int i=0;i<n;i++){ int id=lower_bound(a+i,a+n,a[i]+m)-a; cnt+=n-id; } return cnt>k; } int main() { while(scanf("%d",&n)==1){ k=1LL*n*(n-1)/4; for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(a,a+n); int l=0,r=1000000001,ans; while(l<=r){ int m=(l+r)>>1; if(solve(m)){ ans=m; l=m+1; }else r=m-1; } printf("%d ",ans); } return 0; }