Median
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 5468 |
|
Accepted: 1762 |
Description
Given n numbers, x1, x2, ..., xN, let us calculate th E 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 diff Erences, is even. For example, you had 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 'll be given on the first line. Then N numbers is given, representing x1, x2, ..., xn , ( Xi ≤1,000,000,000 3≤n≤1,00,000)
Output
For each test case, the output of the median in a separate line.
Sample Input
41 3 2 431 10 2
Sample Output
18
The main topic: give you n number, any two number of differences between the total m= (n-1) *N/2 and then let you output these numbers in the middle of the one, the rule for
If M is odd, the middle one is the number of m+1/2, if M is even, the middle number refers to the small number of M/2.
Thinking Analysis: Look at the data range, if the most normal and simplest approach, the complexity O (n^2), will definitely time out, so need to use high-efficiency
The binary algorithm, because A[I]-A[J] is an absolute value, so it is equivalent to a large decrease, so you can sort the array a[n] first, and then
Based on the difference to determine the two-point range, I am sure of 0~a[n-1]-a[0], and then start the binary search, and the check function is mainly statistical smaller than the A[i]+d
Number, if >= (m+1)/2 return True else return false, and in the process of statistics, if the traditional order to find Ken
will also be to the time-out, so should use high-efficiency two-point lookup, I directly used the Upper_bound function, statistics when the attention upper_bound-a
Is the number of array elements for all <=a[i]+x and should be subtracted from all <=a[i] elements (a total of i+1)
Code:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace Std;
int a[100000+5];
int n;
int temp;
BOOL Check (int x)
{
int cnt = 0;
for (int i=0; i<n; i++)
{
int T=upper_bound (A,A+N,A[I]+X)-a;//the number of elements smaller than a[i]+x
cnt+= (t-i-1);///exclude a[i] before those elements, a total of i+1;
}
if (cnt>=temp) return true;
else return false;
}
int main ()
{
while (scanf ("%d", &n)!=eof)
{
for (int i=0;i<n;i++)
scanf ("%d", &a[i]);
Sort (a,a+n);
int m=n* (n-1)/2;
temp= (m+1)/2;
int l=0,r=a[n-1]-a[0];
int ans;
while (L<=R)//two-point search
{
int mid= (L+R) >>1;
if (check (mid))
Ans=mid,r=mid-1;
else l=mid+1;
}
printf ("%d\n", ans);
}
return 0;
}
poj3579 Two-point search + binary lookup