POJ 3579 Median (二分套用)

傳送門

題意: 給N數字, X1, X2, … , XN,我們計算每對數字之間的差值:∣Xi - Xj∣ (1 ≤ i < j ≤ N). 我們能得到 C(N,2) 個差值,現在我們想得到這些差值之間的中位數。
如果一共有m個差值且m是偶數,那麼我們規定中位數是第(m/2)小的差值。
( Xi ≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )
在這裏插入圖片描述
思路: 很神奇的一個題

  • 總共有 n * (n - 1) / 2個差值,那麼比中位數大的就有 n * (n - 1) / 4個數
  • 那麼就可以二分答案ans,並對ans進行判斷
  • 找到原序列a中大於等於ans + a[i]的數的個數x,那麼那麼對應所以得i的x相加得到的cnt若等於 n * (n - 1) / 4的時候就找到答案啦

代碼實現:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 1e6 + 5;

int n, sum;
int a[N];

int cheak(int x){
    int cnt = 0;
    for(int i = 1; i <= n; i ++)
        cnt += n - (lower_bound(a + 1, a + n + 1, x + a[i]) - a - 1);
    return cnt > sum;
}

signed main()
{
    IOS;

    while(~scanf("%d", &n)){

        for(int i = 1; i <= n; i ++)
            scanf("%d", &a[i]);

        sort(a + 1, a + n + 1);
        int l = 1, r = a[n], mid, ans;
        sum = 1LL * n * (n - 1) / 4;

        while(l <= r){
            mid = l + r >> 1;
            if(cheak(mid)) ans = mid, l = mid + 1;
            else r = mid - 1;
        }

        cout << ans << endl;
    }

    return 0;
}

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