Description
Given n numbers, x1,x2, ..., xN, let us calculate the dif Ference 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 ifm, the amount of the D Ifferences, is even. For example, you had to find the third smallest one in the case ofm = 6.
Input
The input consists of several test cases.
In each test case, N 'll be given on the first line. Then N numbers is given, representingx1, x2, ...,xN, ( Xi≤1,000,000,000 3≤n≤1,00,000)
Output
For each test case, the output of the median in a separate line.
Sample Input
41 3 2 431 10 2
Sample Output
18
Source
field=source&key=poj+founder+monthly+contest+%e2%80%93+2008.04.13 ">POJ founder Monthly contest– 2008.04.13, Lei Tao
The main topic: to the number of N, two-phase reduction of m=c (n,2) results, to find (M/2)-th small difference.
Thinking: Two times two points, the first two points to find the difference. For the second time, figure out how many of the numbers on the left are smaller than the number of the first two ticks.
Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import java.io.printwriter;import java.io.streamtokenizer;import java.util.*;p ublic Class Main {static int n;static int a[] = new int[100000];static int m;static int solve (int x,int y,int val,int flag) {Whil E (x<=y) {int mid= (x+y)/2;if (Val-a[mid]<=flag) y=mid-1;elsex=mid+1;} return y;} static Boolean ok (int val) {int j,k=0;for (int i=2;i<=n;i++) {j=solve (1,i-1,a[i],val); k+=i-j-1;} if (k<m) return false;else return true; public static void Main (string[] args) throws IOException {//scanner scan = new Scanner (system.in); Streamtokenizer st = new Streamtokenizer (new BufferedReader (New InputStreamReader (system.in))); PrintWriter out = new PrintWriter (new OutputStreamWriter (System.out)), while (St.nexttoken ()!=streamtokenizer.tt_eof) {n = (int) st.nval;if (n (n-1)/2%2!=0) {m= (n (n-1)/2+1)/2;} elsem=n* (n-1)/2/2;for (int i = 1; I <=n; i++) {st.nexttoken (); a[i] = (int) st.nval;}Arrays.sort (a,1,n+1); int l = 0, R = A[n]-a[1];while (l<=r) {int mid= (l+r)/2;if (OK (mid)) r=mid-1;elsel=mid+1;} Out.println (l); Out.flush ();}}
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
POJ 3579-median