POJ - 3579 Median (二分 + 查找第K大)
2016-08-09 10:54
330 查看
Median
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
Sample Output
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5866 | Accepted: 1947 |
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
不多说,上代码
#include <cstdio> #include <cstring> #include <algorithm> #define FOUT freopen("output.txt", "w+", stdout) using namespace std; typedef long long LL; const int MAXN = 1e5 + 5; int n, A[MAXN]; LL k; bool C(int m){ LL res = 0; for(int i = 0;i < n;i ++){ res += A + n - lower_bound(A + i, A + n, A[i] + m + 1); } return res > k; } int main(){ //FOUT; while(~scanf("%d", &n)){ int Max = 0; for(int i = 0;i < n;i ++){ scanf("%d", &A[i]); Max = max(Max, A[i]); } k = (LL)n * (n - 1) / 4; sort(A, A + n); int lb = -1, ub = Max; while(ub - lb > 1){ int mid = (ub + lb) >> 1; if(C(mid)){ lb = mid; } else{ ub = mid; } } printf("%d\n", ub); } return 0; }
相关文章推荐
- poj 3579 Median (二分搜索之查找第k大的值)
- POJ - 3579 Median(二分搜索,查找第K大的值)
- POJ_3579_Median_(二分,查找第k大的值)
- POJ 3579 Median (查找第k大的值)
- POJ 3579 3685(二分-查找第k大的值)
- poj 3579 Median 二分查找与lower_bound
- 【POJ】3579 - Median 二分->找第K大的值
- POJ 3579 Median 查找中间值 二分
- POJ 3579 Median(二分答案+Two pointers)
- 【POJ】3685 - Matrix 二分->查找第K大的值
- Median - POJ 3579 二分
- POj 3579 Median(二分逼近)
- POJ 3579(二分查找差值中间值)
- poj 3579 Median 中间值(二分搜索)
- [POJ 3579] Median (二分答案+二分查找)
- poj 3685(二分查找第K大的值)
- POJ - 3579 Median 二分 + 尺取法
- POJ - 3685 Matrix (二分搜索:查找第k大的值)
- POJ 3579 median 二分搜索,中位数 难度:3
- POJ 3579 Median(二分)