zoukankan      html  css  js  c++  java
  • POJ 3579 二分

    Median
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 7687   Accepted: 2637

    Description

    Given N numbers, X1X2, ... , 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 = 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 X1X2, ... , XN, ( X≤ 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

    Source

    题意:
    有n个数,每两个数差的绝对值组成一个新的数列,求此数列的中位数偶数时求第m/2小的数
    代码:
    //两重二分,先将a数组从小到大排序,第一重二分中位数的值m,第二重枚举a[i],找到有多少
    //个 |a[j]-a[i]| >= m,将这个数量与n*(n-1)/4比较作为二分的判断条件
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    const int maxn=100009;
    int n,a[maxn];
    ll k;
    bool solve(int m){
        ll cnt=0;
        for(int i=0;i<n;i++){
            int id=lower_bound(a+i,a+n,a[i]+m)-a;
            cnt+=n-id;
        }
        return cnt>k;
    }
    int main()
    {
        while(scanf("%d",&n)==1){
            k=1LL*n*(n-1)/4;
            for(int i=0;i<n;i++)
                scanf("%d",&a[i]);
            sort(a,a+n);
            int l=0,r=1000000001,ans;
            while(l<=r){
                int m=(l+r)>>1;
                if(solve(m)){
                    ans=m;
                    l=m+1;
                }else r=m-1;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    一些基础的前端技术面试问题
    HTTP与HTTPS区别
    XML与JSON
    js的内置对象
    二分法查找
    img下面的留白解决
    大家好
    HEOI2020游记
    CSP-S2019游记
    省选模拟八十六 题解
  • 原文地址:https://www.cnblogs.com/--ZHIYUAN/p/7227848.html
Copyright © 2011-2022 走看看