題目鏈接:http://acdream.info/problem?pid=1735
輸油管道
Time Limit: 2000/1000MS (Java/Others) Memory Limit: 262144/131072KB (Java/Others)
Problem Description
平面上有n個油井,現在要建立一條主干線,用來把所有的油井產出的原油都輸送出去,主干線是平行於x軸的一條直線,每個油井通過一條支線把原油輸送到主干線上,現在給定n個油井在平面上的坐標,那么應該把主干線建在什么地方才能讓所有的支干線的總長度最小呢?

Input
首先一個正整數n,接下來n行每行兩個整數,代表n個油井在平面上的位置。n和坐標都是小於等於1000000的正整數。
Output
輸出總的支干線長度的最小值,每個結果占一行。
Sample Input
2 0 0 10 10
Sample Output
10
解題思路:取y值中位數,總干線建到中位數那口井上,總支干線長度和最小。這道題目求中位數,不需要排序,可以利用快排原理進行部分搜取就可以求出中位數了。
代碼:
1 #include <fstream> 2 #include <iostream> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstdlib> 6 7 using namespace std; 8 9 const int nn=1000005; 10 int a[nn],n,n2,ans; 11 long long cnt; 12 13 int quick_partition(int i,int j); 14 void quick_sort(int s,int t); 15 16 int main(){ 17 //freopen("D:\\input.in","r",stdin); 18 //freopen("D:\\output.out","w",stdout); 19 while(~scanf("%d",&n)){ 20 n2=(n+1)>>1; 21 for(int i=1;i<=n;i++) scanf("%*d%d",&a[i]); 22 quick_sort(1,n); 23 cnt=0; 24 for(int i=1;i<=n;i++) cnt+=(long long)abs(a[i]-ans); 25 printf("%lld\n",cnt); 26 } 27 return 0; 28 } 29 int quick_partition(int i,int j){ 30 a[0]=a[i]; 31 while(i<j){ 32 while(i<j&&a[j]>=a[0]) j--; 33 if(i<j) a[i]=a[j],i++; 34 while(i<j&&a[i]<=a[0]) i++; 35 if(i<j) a[j]=a[i],j--; 36 } 37 a[i]=a[0]; 38 return i; 39 } 40 void quick_sort(int s,int t){ 41 if(s<t){ 42 int tmp=quick_partition(s,t); 43 if(tmp==n2){ 44 ans=a[tmp]; 45 }else if(tmp<n2){ 46 quick_sort(tmp+1,t); 47 }else{ 48 quick_sort(s,tmp-1); 49 } 50 }else if(s==t) 51 ans=a[s]; 52 }
