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.
InputThe 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 )
For each test case, output the median in a separate line.
4 1 3 2 4 3 1 10 2Sample Output
1 8
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
long long n,m;
int ai[100005];
int fun(int mid)
{
int sum=0,r=1;
for(int i=0;i<n;i++)
{
while(ai[r]-ai[i]<=mid&&r<n) r++;
sum+=r-i-1;//減1 是因爲上面多加了一個 1;
}
if(sum>=m) return 1;
return 0;
}
int main()
{
{
for(int i=0;i<n;i++)
scanf("%d",&ai[i]);
m=n*(n-1)/2;
if(m%2==0) m=m/2;
else m=(m+1)/2;
sort(ai,ai+n);
int q=0,w=ai[n-1]-ai[0],mid;
while(q<=w)
{
mid=(q+w)/2;
if(fun(mid))
w=mid-1;/*爲什麼是把 mid-1 賦值給 w 呢?是因爲,如果滿足了那個 m 的話,說明小於 這個差是比較多的,所以 二分是要把這個範圍縮小,變成 [q,mid-1]*/
else
q=mid+1;
}
printf("%d\n",w+1);
}
}