• POJ 3579 Median(二分答案)


    Median
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 11599   Accepted: 4112

    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个数,然后求它们两两相减的绝对值,然后找出这些绝对值的中位数

     

    【分析】

    1、先对n个数排序,那么最后的结果ans一定满足0<=ans<an-a1

    2、我们用二分进行逼近。l=0r=an-a1mid=l+r/2

    3、很明显是原数组两个数相减的绝对值<mid个数,和>mid的个数进行比较。(绝对值的个数<mid,ans[mid,r]区间,否则在[l,mid]区间内)

    4、以求一个数减去a[1]的值小于mid的个数为例,我们找到一个a[i]>=a[1]+mid时最小的一个i,那么数组[1,i)值减去a[1],都小于mid,这样枚举i就可以求得两数相减差值(的绝对值)小于mid的个数。

     

    【代码】

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    inline int read(){
    	register char ch=getchar();register int x=0;
    	for(;ch<'0'||ch>'9';ch=getchar());
    	for(;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+ch-'0';
    	return x;
    }
    const int N=2e5+5;
    int n,a[N];ll m;
    inline bool check(int now){
    	ll sum=0;
    	for(int i=1;i<=n;i++)
    		sum+=lower_bound(a+i+1,a+n+1,a[i]+now)-(a+i)-1;
    	return m&1?sum<=m/2:sum<m/2;
    }
    int main(){
    	while(scanf("%d",&n)==1){
    		for(int i=1;i<=n;i++) a[i]=read();
    		sort(a+1,a+n+1);m=1LL*n*(n-1)>>1;
    		int l=0,r=a[n]-a[1],mid,ans=0;
    		while(l<=r){
    			mid=l+r>>1;
    			if(check(mid)){
    				ans=mid;
    				l=mid+1;
    			}
    			else{
    				r=mid-1;
    			}
    		}
    		printf("%d
    ",ans);
    	}
    	return 0;
    }

     

     

  • 相关阅读:
    如何提高系统吞吐性能
    若依项目安装注意事项
    VueTreeselect
    【win10 系统】idea 修改 Git 密码和账号方法
    事件总线
    HangFire【一】
    gRPC学习一【基础】
    .NET Core API 网关Ocelot
    Quartz【一】
    .NET Core API 自动生成实体类
  • 原文地址:https://www.cnblogs.com/shenben/p/10319538.html
Copyright © 2020-2023  润新知