【Jason's_ACM_解题报告】Age Sort

来源:互联网 发布:linq for java 编辑:程序博客网 时间:2024/06/01 15:15

Age Sort

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
5
3 4 2 1 5
5
2 3 2 3 1
0

Sample Output
1 2 3 4 5
1 2 2 3 3


此题由于N的取值范围在1~2000000之间,所以无法使用快速排序,由于年龄的取值范围在1~99之间,范围很小,所以使用计数排序是能够承受的。


但由于这一部分是高效算法设计,所以Liu提供了一种通过库函数和宏定义逐字符输入输出的方法来提高时间效率。

全局变量减少系统开销,另外此题不用考虑0的输出,因为年龄最小为1.

这种方式提高时间效率主要利用了cctype头文件中的isdigit函数,它仅识别0~9之间的数字,此外该头文件中还含有2两个十分有用的函数tolower和toupper.

下面贴上其他的一些函数.




附代码如下:

普通计数排序:

#include<cstdio>#include<cstring>using namespace std;#define clr(x) (memset(x,0,sizeof(x)))int age[100];int main(){int n,x;while(scanf("%d",&n)==1&&n){clr(age);int flag=true;for(int i=0;i<n;i++){scanf("%d",&x);age[x]++;}for(int i=1;i<100;i++){if(age[i])while(age[i]--){if(flag){printf("%d",i);flag=false;}else printf(" %d",i);}}printf("\n");}return 0;}

cctype逐字节输入输入:

#include<cstdio> #include<cstring>#include<cctype>using namespace std;#define clr(x) (memset(x,0,sizeof(x)))#define MAXN (100)int a[MAXN];bool flag;char buf[2];int n;inline int readint(){char c=getchar();while(!isdigit(c))c=getchar();int d=0;while(isdigit(c)){d=d*10+c-'0';c=getchar();}return d;}inline void writeint(int x){int len=0;while(x){buf[len]=x%10+'0';x=x/10;len++;}for(int i=len-1;i>=0;i--)putchar(buf[i]);}int main(){while(n=readint()){clr(a);for(int i=0;i<n;i++)a[readint()]++;flag=true;for(int i=1;i<100;i++){if(a[i])while(a[i]--){if(flag){flag=false;writeint(i);}else{putchar(' ');writeint(i);}}}putchar('\n');} return 0;}


0 0
原创粉丝点击