POJ3579

1. 题面:

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.

2. 思路

  • 先将a[n]排序
  • x 为中位数 => |ajai|<x 的个数恰好为一半 => 所有的 aj>ai aj<x+ai 个数为一半
    • x 从 [0,max{|ajai|}] 中二分查找
    • 枚举i,在a[n]中利用uppper_bound()二分查找 x+ai<aj(aj>ai) 的个数,若恰为一半,则x为所求

3. 代码

#include <iostream>
#include <algorithm>
#include <cstdio>

using namespace std;

int a[100000 + 5];
int n;
int m;

bool uppereq(int k) {
    int cnt = 0;
    for (int i = 0; i < n; i++) {
    int temp = (upper_bound(a, a + n, a[i] + k) - a)-1;            
    //返回为地址,所以用&a[0]来修正,得到所有符合要求的元素的最大下标
        cnt += temp - i;
    }
    if (cnt >=m) return true;
    else return false;
}

int main() {
    //while (cin>>n) {
    while (scanf("%d", &n) != EOF){
        int ans ;
        m = ((n*(n-1)>>1) + 1)>>1;
        for (int i = 0; i < n; i++)
            //cin >> a[i];
            scanf("%d", &a[i]);
        sort(a, a + n);
        int up = a[n - 1] - a[0];
        int low = 0;
        //for (; low <= up;) {
        while(low<=up){
            int mid = (low + up) >> 1;
            if (uppereq(mid)) { ans = mid; up = mid - 1; }  
            //uppereq(mid)函数用作一个“大于”信号
            else low = mid + 1;
        }
        //cout << ans << endl;
        printf("%d\n", ans);
    }
    return 0;
}

4. 所得

  1. 对二分法的理解:
    • 范围:适用于有序序列,可为各元素存在的有序数组,如本题a[n],也可为确定的数据范围,如本题[0,a[n-1]-a[0]]
    • 条件:需要一个“大于/小于”的信号,如本题中设置的bool upppereq()
    • 赋值:二分法实现时,注意为l=mid+1 r=mid-1,缺少“1”则可能导致边界情况跳不出循环
  2. 实现细节:
    • cin 输入慢于scanf, 本题使用cin则会TLE
    • 注意奇偶性 / 边界的±1

5.参考

当蜗牛有了理想 - POJ3579+二分查找

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值