国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

POJ 3579 Median(2次二分)

2019-11-10 20:22:15
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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.

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, representingX1, 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
41 3 2 431 10 2Sample Output
18

  思路:本題直接使用暴力法,時(shí)間復(fù)雜度約為n^2,超時(shí),所以采用二分法。

  先把差值分出來(lái),再用二分法驗(yàn)證差值是否符合要求。

#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的查找函數(shù)
    }    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;}

總結(jié):lower_bound函數(shù)的引用

 


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 祁门县| 罗源县| 东光县| 永福县| 杨浦区| 南昌县| 承德市| 洞头县| 宜章县| 斗六市| 山阴县| 北票市| 团风县| 庆城县| 广州市| 礼泉县| 福泉市| 若尔盖县| 北宁市| 武义县| 玉溪市| 巴彦淖尔市| 南江县| 黄平县| 巴林左旗| 视频| 上饶市| 澎湖县| 石林| 安徽省| 黄梅县| 万载县| 武宣县| 璧山县| 资中县| 张家界市| 光山县| 教育| 南皮县| 徐汇区| 永胜县|