这个题目可以不用排序来完成,我之所以用这了是因为这个题被ACM划分到排序这一章节了。 // Vito's Family.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int TestRound=0;// the count of test data; cin>>TestRound; for(int round=0;round<TestRound;++TestRound) { int NoFamily=0;// amount of family; cin>>NoFamily; int *StreetFamily=new int[NoFamily];// No. of every family; int Vito=0;// the street number of Vito; int DistanceAll=0; // the calculation of all the distance between Vito and every family; for(int NoStr=0;NoStr<NoFamily;++NoStr)cin>>StreetFamily[NoStr]; //Sort the No. street; for(int SortStreet1=NoFamily-1;SortStreet1>0;--SortStreet1) { for(int SortStreet2=0;SortStreet2<SortStreet1;++SortStreet2) { if(StreetFamily[SortStreet2]>StreetFamily[SortStreet2+1]) { int tmp=StreetFamily[SortStreet2+1]; StreetFamily[SortStreet2+1]=StreetFamily[SortStreet2]; StreetFamily[SortStreet2]=tmp; } } } //Get calculation of the mininum distance ; int MinDistance=0; int TVito=0; if(((StreetFamily[0]+StreetFamily[NoFamily-1])%2)!=0) { TVito=(StreetFamily[0]+StreetFamily[NoFamily-1])/2; for(int i=0;i<NoFamily;++i) MinDistance=MinDistance+abs(TVito-StreetFamily[i]); Vito=TVito; DistanceAll=MinDistance; TVito=(StreetFamily[0]+StreetFamily[NoFamily-1])/2+1; for(int j=0;j<NoFamily;++j) MinDistance=MinDistance+abs(TVito-StreetFamily[j]); if(MinDistance<DistanceAll) { Vito=TVito; DistanceAll=MinDistance; } } else { Vito=(StreetFamily[0]+StreetFamily[NoFamily-1])/2; for(int i=0;i<NoFamily;++i) DistanceAll=DistanceAll+abs(Vito-StreetFamily[i]); } cout<<DistanceAll<<"/n"; delete []StreetFamily; } return 0; }