ACM_排序

除了sort,你还会什么

Time Limit: 1000/500ms (Java/Others)

Problem Description:

给出若干人的年龄(1~100之间的整数),把它们按照从小到大的顺序输出。

Input:

输入包含多组测试数据。每组数据的第一行为一整数 n,(0<n<=2 000 000),即居民总数;下一行输入 n 个整数,表示各居民的年龄。(输入文件约有20 MB,而内存限制只有2 MB,除了sort(),你还会什么...)

Output:

对于每一组数据,按照从小到大的顺序输出各居民的年龄。相邻年龄用空格隔开。

Sample Input:

3
56 56 56
5
99 91 89 63 91

Sample Output:

56 56 56 
63 89 91 91 99 
解题思路:题目中给出n的最大值为2*10^6,也就是直接调用sort函数的话,会超时,因为其时间复杂度是O(nlogn),但是注意年龄的范围只有1~100,相对n来说很小,也就是说我们可以利用一个数组来存相同年龄人的个数,然后从1~100直接输出每个值就可以了,注意要用C语言的输入输出,不要会超时!!!
AC代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     int n,x,a[101];
 6     while(~scanf("%d",&n)){
 7         memset(a,0,sizeof(a));
 8         for(int i=1;i<=n;++i){
 9             scanf("%d",&x);a[x]++;
10         }
11         for(int i=1,m=0;i<=100;++i){
12             for(int j=1;j<=a[i];++j){
13                 ++m;printf("%d%s",i,m<n?" ":"\n");
14             }
15         }
16     }
17     return 0;
18 }

猜你喜欢

转载自www.cnblogs.com/acgoto/p/9010217.html