这道题目考查的是基本的排序算法的选择和使用,都说到是算法的选择了,当然对时间有一定的要求。本博主尝试了基本常见算法,如时间复杂度是O(n*n)的冒泡算法,插入算法,选择算法都是不能通过的。那么就要选择时间复杂度更优的算法了,粗略想了一下,就快排和堆排序比较熟悉,于是就采用这种算法编写程序,最后都通过了。
快排和堆排序(优先队列)都有现成的类来调用,分别是<algorithm>和<queue>,实现起来相当方便。
用快排实现如下:
1 // Problem#: 4923 2 // Submission#: 1435620 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University 6 #include <stdio.h> 7 #include <algorithm> //这个包含一个sort()的快排函数 8 using namespace std; 9 int main() 10 { 11 int n=0,m=0; 12 scanf("%d%d",&n,&m); 13 while(n) 14 { 15 int *a,i=0; 16 a=new int[n]; 17 for(i=0;i<n;i++) 18 scanf("%d",&a[i]); 19 sort(a,a+n); 20 printf("%d",a[0]); 21 for(i=m;i<n;i=i+m) 22 { 23 printf(" %d",a[i]); 24 } 25 printf("\n"); 26 scanf("%d%d",&n,&m); 27 } 28 return 0; 29 }
用优先队列进行排序:
1 // Problem#: 4923 2 // Submission#: 1436251 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University 6 #include <stdio.h> 7 #include <queue> 8 using namespace std; 9 int main() 10 { 11 int n=0,m=0; 12 scanf("%d%d",&n,&m); 13 while(n) 14 { 15 priority_queue<int,vector<int>,greater<int> > q; //小堆优先序列 16 int i=0,temp; 17 for(i=0;i<n;i++) 18 { 19 scanf("%d",&temp); 20 q.push(temp); 21 } 22 printf("%d",q.top()); 23 q.pop(); 24 int k=m; 25 for(i=1;i<n;i++) 26 { 27 if(i==k) 28 { 29 printf(" %d",q.top()); 30 k=k+m; 31 } 32 q.pop(); 33 } 34 printf("\n"); 35 scanf("%d%d",&n,&m); 36 } 37 return 0; 38 }
经测试,第一种用快排用时0.05s,第一种堆用时0.06s。原因应该在于输出时访问数据的时间,数组可以直接访问,而堆必须一个个pop出来后再输出的,用时就多了点。