1 / 6

士兵站队问题 --- 解题报告

士兵站队问题 --- 解题报告. By : 林宗明 NO60320081 . 解题思路与正确性 . 算法实现与 code . 复杂性. 解题思路与正确性 : 要求士兵排成一行需要的最少移动步数,先 观察 最 终 n 个士兵的位置坐标: (x,y),(x+1,y), … ,(x+n-1,y). 可以发现规律: 最终 y 轴坐标是同一固定值,而当把 x 轴坐标依次减 0 , 1 , 2 , … , (n-1) 后所得到的 x 轴坐标也是同一固定值。

chase
Download Presentation

士兵站队问题 --- 解题报告

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 士兵站队问题---解题报告 By:林宗明 NO60320081 .解题思路与正确性 .算法实现与code .复杂性

  2. 解题思路与正确性: 要求士兵排成一行需要的最少移动步数,先观察最终n个士兵的位置坐标:(x,y),(x+1,y),…,(x+n-1,y). 可以发现规律:最终y轴坐标是同一固定值,而当把x轴坐标依次减0,1,2,…,(n-1)后所得到的x轴坐标也是同一固定值。 因此,依据在一组数中,各数距中位数(这里即为士兵最终位置的x轴和y轴的那两个固定值)之绝对差,其和最小,可算出最少的移动步数。 s1 s2 s3 s4 s5

  3. 算法实现: 步骤: 1、用快速排序分别对x轴坐标和y轴坐标进行排序 和处理(注意边界问题)。 2、分别找出中位数。 3、分别算x轴和y轴各坐标值到中位数的绝对差之和,最后把这两个值相加即为所求最少步数值。

  4. Code1(y轴上移动步数): • int count_Y(int data_Y[],int n) • { • int count=0; • QuickSort(data_Y,0,n-1); • int midY=n/2; • for(int i=0;i<n;i++) • count=count+(int)fabs(data_Y[i]-data_Y[midY]); • return count; • }

  5. Code2(x轴上移动步数): • int count_X(int data_X[],int n) • { • int count=0; • QuickSort(data_X,0,n-1); • for(int i=0;i<n;i++) • data_X[i]=data_X[i]-i; • int midX=0; • QuickSort(data_X,0,n-1); • midX=n/2; • int mid=data_X[midX]; • if(mid<-10000) • mid=-10000; • if(mid+n-1>10000) • mid=10000-n+1; • for(int j=0;j<n;j++) • count=count+(int)fabs(data_X[j]-mid); • return count; • }

  6. 复杂性: 算法定义两个一维数组*X和*Y,故空间复杂度为2*O(n). 时间复杂度跟所选用的排序方法有关,这里用快速排序,故时间复杂度为O(nlogn).

More Related