POJ:3579-Median(二分+尺取寻找中位数)
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數字, X1, X2, … , XN,我們計算每對數字之間的差值:∣Xi - Xj∣ (1 ≤ i < j ≤ N). 我們能得到 C(N,2) 個差值,現在我們想得到這些差值之間的中位數。
如果一共有m個差值且m是偶數,那么我們規定中位數是第(m/2)小的差值。
輸入包含多測
每個測試點中,第一行有一個NThen N 表示數字的數量。
接下來一行由N個數字:X1, X2, … , XN
( Xi ≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )
解題心得:
#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;//差值的個數if(tot%2 == 0) {//中位數在第幾個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() {//每次枚舉一個中位數的值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; }
轉載于:https://www.cnblogs.com/GoldenFingers/p/9107120.html
總結
以上是生活随笔為你收集整理的POJ:3579-Median(二分+尺取寻找中位数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对oracle sql的一些总结
- 下一篇: USACO-Section2.3 Lon