在河边有N户人家,他们每天都需要到河边去打水,后来政府拔款给大家修建一个水库。
每户人家到水库的最短距离为沿河方向的距离差,问如何选择水库的位置,使所有人到水库的距离和最短?
2
2
1 3
1
3
2
0
#include<stdio.h>#include<string.h>sortquickly(int a[],int lenth){ int mid; mid = a[0]; int i,j; i=0; j=lenth-1; if(lenth>1) { while(i<j) { for(;j>i;j--) { if(a[j]<mid) { a[i++]=a[j]; break; } } for(;i<j;i++) { if(a[i]>mid) { a[j--]=a[i]; break; } } } a[i]=mid; sortquickly(a,i); sortquickly(a+i+1,lenth-i-1); }}main(){ int i,a[100001],lenth,N,h,p,o,mid,x,T,j; long sum; scanf("%d",&T); for(j=0;j<T;j++) { sum=0; scanf("%d",&N); h=N; for(i=0;i<N;i++) scanf("%d",&a[i]); sortquickly(a,N); if(h%2!=0) { p=(h-1)/2; mid=a[p]; for(o=0;o<p;o++) { x=mid-a[o]; sum=sum+x; } for(o=p+1;o<h;o++) { x=a[o]-mid; sum=sum+x; } } if(h%2==0) { p=h/2; p=p-1; mid=a[p]; for(o=0;o<p;o++) { x=mid-a[o]; sum=sum+x; } for(o=p+1;o<h;o++) { x=a[o]-mid; sum=sum+x; } } printf("%ld\n",sum);}}
原文:http://www.cnblogs.com/SSYYGAM/p/4215500.html