Median(lower_bound)

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

 题意:给定N个数,这些数字两两求差构成C(N,2)个数值,求这C(N,2)个数的中位数。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#define rush() int T;cin>>T;while(T--)
#define go(a) while(cin>>a)
#define ms(a,b) memset(a,b,sizeof a)
#define E 1e-8
using namespace std;
typedef long long ll;
const int idata=1e5+5;

int n,m,t,_;
int i,j,k;
ll cnt,num,ans;
int p[idata];

bool judge(int mid)
{
    ll sum=0;
    for(i=0;i<n-1;i++){
        //寻找
        sum+=n-(lower_bound(p,p+n,p[i]+mid)-p);
    }
    return sum>num/2;
}
int main()
{
    cin.tie(0);
    iostream::sync_with_stdio(false);
    while(cin>>n)
    {
        for(i=0;i<n;i++){
            cin>>p[i];
        }
        num=n*(n-1)/2;
        sort(p,p+n);
        int l=0,r=p[n-1]-p[0]+1;
        while(r-l>1){
            int mid=(l+r)/2;
            if(judge(mid)) l=mid;
            else r=mid;
        }
        cout<<l<<endl;
    }
    return 0;
}
原创文章 410 获赞 16 访问量 3万+

猜你喜欢

转载自blog.csdn.net/C_Dreamy/article/details/105861547