【POJ 3579】 Median 二分答案 + lowerbound

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.

題意:給n個數,在C(n,2)個組合數的差值絕對值中找到第k小的

思路(二分答案):

·因爲是組合數,有無序的性質,所以我們可以先對數組排序,這樣方便後續操作,求差值的時候只需要後面減去前面的即可。
·接着二分中位數,拿到一個mid,限制條件怎麼設置呢?我們想mid什麼時候需要向上移動?不就是比它大的數比組合數的一半多嗎?說明這個mid比中位數小,所以我們就要上調mid。反之這說明mid太大,比它小的數不夠一半。
·那麼就只剩下核心的判斷比mid大的數的數量了。因爲我們前面已經排好序,而且手上有個mid,所以我們可以對數組的每個位置枚舉,看看大於等於mid+a[i]的數有多少個,累加結果和組合數一半判斷即可。總體複雜度O(nlognlogn)

AC代碼:

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include <queue>
#include<vector>
#define FAST ios::sync_with_stdio(false)
#define abs(a) ((a)>=0?(a):-(a))
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define rep(i,a,n) for(int i=a;i<=n;++i)
#define per(i,n,a) for(int i=n;i>=a;--i)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define maxn 100000+500
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;

inline ll read()
{
    ll x = 0;
    char ch = getchar();
    while(ch>'9'||ch<'0') ch = getchar();
    while(ch>='0'&&ch<='9') x = (x<<3) + (x<<1) + ch - '0',  ch = getchar();
}

ll a[maxn];
ll n,m;

ll cal(ll x)
{
    ll cnt = 0;
    for(ll i=1;i<=n;i++)
    cnt += (a+n+1) - lower_bound(a+i+1,a+1+n,a[i]+x);
    return cnt<=m/2;
}

int main()
{
    while(~scanf("%lld",&n))
    {
        for(ll i=1;i<=n;i++)
        scanf("%lld",&a[i]);
        sort(a+1,a+1+n);
        ll L = 1e15, R = -1;
        for(ll i=2;i<=n;i++)
        L =min(a[i]-a[i-1],L);
        R = a[n] ;
        m = n*(n-1)/2;
        while(L<R-1)
        {
            ll mid = (L+R)>>1;
            if(cal(mid))
            R = mid;
            else
            L = mid;
        }
        printf("%lld\n",L);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章