Sicily.1306 Sorting Algorithm

     这道题目考查的是基本的排序算法的选择和使用,都说到是算法的选择了,当然对时间有一定的要求。本博主尝试了基本常见算法,如时间复杂度是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出来后再输出的,用时就多了点。

   

转载于:https://www.cnblogs.com/lfwllq/archive/2012/06/12/2546718.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值