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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

POJ:3579-Median(二分+尺取寻找中位数)

發(fā)布時間:2025/3/15 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 POJ:3579-Median(二分+尺取寻找中位数) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Median

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9201 Accepted: 3209

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.

Sample Input

4
1 3 2 4
3
1 10 2

Sample Output

1
8


中文題意:

給N數(shù)字, X1, X2, … , XN,我們計(jì)算每對數(shù)字之間的差值:∣Xi - Xj∣ (1 ≤ i < j ≤ N). 我們能得到 C(N,2) 個差值,現(xiàn)在我們想得到這些差值之間的中位數(shù)。

如果一共有m個差值且m是偶數(shù),那么我們規(guī)定中位數(shù)是第(m/2)小的差值。

輸入包含多測
每個測試點(diǎn)中,第一行有一個NThen N 表示數(shù)字的數(shù)量。
接下來一行由N個數(shù)字:X1, X2, … , XN
( Xi ≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )


解題心得:

  • 首先要知道的是n個數(shù)字可以得到C(N,2)個數(shù)字,那么要得到中位數(shù),如果是偶數(shù)就要得到第n/2大的數(shù)字,如果是奇數(shù)就要得到第n/2+1個數(shù)字。
  • 具體做法可以先將給出的數(shù)字排序,然后每次二分枚舉一個中位數(shù)(O(logn)),然后驗(yàn)證比這個中位數(shù)小的數(shù)字有多少個,在驗(yàn)證比這個中位數(shù)小的數(shù)字有多少個的時候可以選擇尺取法(具體實(shí)現(xiàn)看代碼,O(n)),這樣就在O(nlogn)的復(fù)雜度內(nèi)完成。

  • #include <algorithm> #include <stdio.h> #include <cstring> using namespace std; const int maxn = 1e5+100;int n,num[maxn]; long long tot;void init() {tot = 0;tot = (long long)n*(n-1)/2;//差值的個數(shù)if(tot%2 == 0) {//中位數(shù)在第幾個tot /=2;}elsetot = tot/2 + 1;for(int i=0;i<n;i++) {scanf("%d",&num[i]);}sort(num,num+n); }bool checke(int va) {int t = 0;long long sum = 0;for(int i=0;i<n;i++) {while(t < n && num[t] - num[i] <= va)//尺取法看比va小的值有多少個t++;sum += t-i-1;}if(sum < tot)return true;return false; }int binary_search() {//每次枚舉一個中位數(shù)的值int l,r;l = 0, r = 1e9+100;while(r - l > 1) {int mid = (l + r) >> 1;if(checke(mid))l = mid;elser = mid;}return r; }int main() {while(scanf("%d",&n ) != EOF) {init();int ans = binary_search();printf("%d\n",ans);}return 0; }

    轉(zhuǎn)載于:https://www.cnblogs.com/GoldenFingers/p/9107120.html

    總結(jié)

    以上是生活随笔為你收集整理的POJ:3579-Median(二分+尺取寻找中位数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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