Median(查找中位数)

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 = 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
#include
#include
#define ll long long
#define inf 0x3f3f3f3f
const double esp=1e-7;
const int maxn=100010;
using namespace std;
int n,m,l,r;
int a[maxn];
int check(int d)
{
    int sum=0;
    for(int i=0;i=m) return 1;
    else return 0;
}
int er_fen(int l,int r)
{

    while(r>=l)
    {
        int mid=(l+r)/2;
        if(check(mid)) r=mid-1;
        else l=mid+1;
    }
    return l;
}
int main()
{
    while(~scanf("%d",&n))
    {
        int c=n*(n-1)/2;
        if(c%2==0) m=c/2;
        else m=c/2+1;
        for(int i=0;i

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;
}

 

你可能感兴趣的:(二分)