Age Sort Input: Standard Input Output: Standard Output |
You are given the ages (in years) of all people of a country with at least 1 year of age. You know that no individual in that country lives for 100 or more years. Now, you are given a very simple task of sorting all the ages in ascending order.
Input
There are multiple test cases in the input file. Each case starts with an integer n (0<n<=2000000), the total number of people. In the next line, there are n integers indicating the ages. Input is terminated with a case where n = 0. This case should not be processed.
Output
For each case, print a line with n space separated integers. These integers are the ages of that country sorted in ascending order.
Warning: Input Data is pretty big (~ 25 MB) so use faster IO.
Sample Input Output for Sample Input
5 3 4 2 1 5 5 2 3 2 3 1 0 | 1 2 3 4 5 1 2 2 3 3 |
Note: The memory limit of this problem is 2 Megabyte Only.
本题题意:
给定若干居民的年龄(1-100之间的整数),把他们按照从小到大的顺序输出。
输入包含多组测试数据,第一行一个整数n(0<n<=2000 000),即居民总数,下一行包含n个表示年龄的整数,输入结束标志:n = 0.
输入文件约有25MB,而内存限制只有2MB。
分析:
由于数据太大,内存限制太紧,根本无法使用快速排序,因此可以使用计数排序(桶排序)的方法。


#include<cstdio> #include<cstring> //使用memset using namespace std; int main() { int n , num[101]; while(scanf("%d" , &n) == 1 && n) { int i , j , temp; memset(num , 0 , sizeof(num)); for(i = 0; i < n; i++) { scanf("%d" , &temp); num[temp]++; } int first = 1; for(i = 1; i <= 100; i++) { for(j = 0; j < num[i]; j++) { if(!first) printf(" "); first = 0; printf("%d" , i); } } printf("\n"); } return 0; }
还有一种更加节约时间的代码,当输入的数据量很大时,使用printf和scanf函数,如果还不行,就要使用字符一个一个的输入。
由于使用字符的形式一个一个的输入,所以将函数定义为内联函数。
解题代码如下:


#include<cstdio> #include<cctype> //使用isdigit宏的头文件 #include<cstring> using namespace std; inline int readin() //使用内联函数 { int c; c = getchar(); while(!isdigit(c)) c = getchar(); int x = 0; while(isdigit(c)) { x = x * 10 + (c - '0'); c = getchar(); } return x; } inline void writeout(int n) { int i = 0 , j; int temp[3]; if(n == 0) { temp[0] = 0; i++; } else { while(n) { temp[i++] = n % 10; n /= 10; } } for(j = i-1; j >=0; j--) putchar('0' + temp[j]); } int main() { int n , num[101]; //freopen("data.txt","r",stdin);//读 while(n = readin()) { int i , j; memset(num , 0 , sizeof(num)); for(i = 0; i < n; i++) { num[readin()]++; } int first = 1; for(i = 1; i <= 100; i++) { for(j = 0; j < num[i]; j++) { if(!first) putchar(' '); first = 0; writeout(i); } } putchar('\n'); } return 0; }
可以看出,两个程序的运行时间还是成倍数差别的。