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 ifm,the amount of the differences, is even. For example, you have to find the third smallest one in the case ofm = 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, representingX1, X2, ... ,XN, ( Xi≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )
OutputFor each test case, output the median in a separate line.
Sample Input41 3 2 431 10 2Sample Output18思路:本題直接使用暴力法,時間復雜度約為n^2,超時,所以采用二分法。
先把差值分出來,再用二分法驗證差值是否符合要求。
#include<algorithm>#include<cstdio>#include<cstdlib>using namespace std;int n,m;int str[100005];int judge(int mid){ int cnt=0; for(int i=0;i<n;i++) { cnt+=n-(lower_bound(str,str+n,str[i]+mid)-str);//C++中STL的查找函數} return cnt>m?1:0;}int main(){ //freopen("e://in.txt","r",stdin); while(scanf("%d",&n)==1) { m=n*(n-1)/4; for(int i=0;i<n;i++) scanf("%d",&str[i]); sort(str,str+n); int left=0,right=str[n-1]+str[0],mid; while(left<=right) { mid=(left+right)/2; if(judge(mid)) left=mid+1; else right=mid-1; } printf("%d/n",left-1); } return 0;}總結:lower_bound函數的引用
新聞熱點
疑難解答