poj3579 二分搜索+二分查找


Median
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5468   Accepted: 1762

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 m = 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
題目大意:給你n個數,任意兩個數之間的差共有m=(n-1)*n/2種然后讓你輸出這些數中間的那一個,規則為
若m為奇數,中間的那一個為第(m+1)/2小的數,若m為為偶數,中間那個數指的是第m/2小的數。
思路分析:看了一下數據范圍,如果用最正常最簡單的做法,復雜度O(n^2),肯定會超時,因此需要采用高效率的
二分算法,因為a[i]-a[j]是取了絕對值的,因此就相當於是大的減小的,因此可以將數組a[n]先sort排序,然后
根據差值確定二分范圍,我確定的是0~a[n-1]-a[0],然后開始二分搜索,而check函數則主要是統計比a[i]+d小的
數有多少個,如果>=(m+1)/2就return true else return false,而在統計的過程中如果用傳統的順序查找肯
定也會到致超時,所以應該使用高效率的二分查找,我直接用了upper_bound函數,統計的時候注意upper_bound-a
是所有<=a[i]+x的數組元素的個數,應該減去所有<=a[i]的元素(共i+1個)
代碼:
#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;//比a[i]+x小的元素的個數
       cnt+=(t-i-1);//排除a[i]之前的那些元素,共有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)//二分搜索
         {
             int mid=(l+r)>>1;
             if(check(mid))
              ans=mid,r=mid-1;
             else l=mid+1;
         }
         printf("%d\n",ans);
    }
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM