日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Median(POJ-3579)

發(fā)布時(shí)間:2025/3/17 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Median(POJ-3579) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Problem 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.

Examples

Input

4
1 3 2 4
3
1 10 2

Output

1
8

題意:每組數(shù)據(jù)給出 n 個(gè)數(shù),任意兩個(gè)數(shù)之間的差的絕對(duì)值有 C(N,2)=(n-1)*n/2 種,要求輸出這些數(shù)中間的那一個(gè),若?C(N,2) 為偶數(shù),中間那個(gè)數(shù)即為第?C(N,2)/2 小的數(shù),若?C(N,2) 為奇數(shù),中間那個(gè)數(shù)即為 第 (C(N,2)+1)/2 小的數(shù)

思路:n 是 100000,暴力的話時(shí)間復(fù)雜度能到 O(n^2) 左右,一定會(huì)超時(shí),因此需要用二分來找

根據(jù)題意,兩個(gè)數(shù)的差取了絕對(duì)值,可看作數(shù)組 a[n] 中,任意兩個(gè)數(shù) a[i]、a[j] 一定是大的減小的,故可以對(duì)數(shù)組先進(jìn)行排序,然后根據(jù)差值來確定二分的范圍:0~a[n]-a[1],從而進(jìn)行二分

Source Program

#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include<stack> #include<queue> #include<deque> #include<vector> #include<set> #include<map> #define PI acos(-1.0) #define E 1e-6 #define INF 0x3f3f3f3f #define N 100001 #define LL long long const int MOD=998244353; const int dx[]={-1,1,0,0}; const int dy[]={0,0,-1,1}; using namespace std; int n; int a[N]; bool check(int x){int cnt=0;for(int i=0;i<n;i++){int left=i,right=n-1;while(left<=right){int mid=(left+right)>>1;if(a[mid]<a[i]+x)left=mid+1;elseright=mid-1;}cnt+=left-i-1;//cnt+=upper_bound(a,a+n,a[i]+x)-a-i-1;}int m=n*(n-1)/2;//C(n,2)m=(m+1)/2;return cnt>=m; } int main(){while(scanf("%d",&n)!=EOF&&n){for(int i=0;i<n;i++)scanf("%d",&a[i]);sort(a,a+n);int left=0,right=a[n-1];while(left<=right){int mid=(left+right)/2;if(check(mid))right=mid-1;elseleft=mid+1;}printf("%d\n",right);}return 0; }

?

新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎(jiǎng)!定制產(chǎn)品紅包拿不停!

總結(jié)

以上是生活随笔為你收集整理的Median(POJ-3579)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。