zoukankan      html  css  js  c++  java
  • UVA 11462 Age Sort(计数排序法 优化输入输出)

    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 (0<n<=2000000), the total number of people. In the next line, there are integers indicating the ages. Input is terminated with a case where = 0. This case should not be processed.

    Output

    For each case, print a line with 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

    Output for Sample Input

    1 2 3 4 5

    1 2 2 3 3

    题目大意:给定若干居民的年龄(都是1-100之间的整数),把他们按照从小到大的顺序输出。

    分析:年龄排序。由于数据太大,内存限制太紧(甚至都不能把他们全部读进内存),因此无法使用快速排序方法。但整数范围很小,可以用计数排序法。

    代码如下:

     1 #include<cstdio>
     2 #include<cstring>
     3 #include<cctype> // 为了使用isdigit宏
     4 
     5 inline int readint() {
     6   char c = getchar();
     7   while(!isdigit(c)) c = getchar();
     8 
     9   int x = 0;
    10   while(isdigit(c)) {
    11     x = x * 10 + c - '0';
    12     c = getchar();
    13   }    
    14   return x;
    15 }
    16 
    17 int buf[10]; // 声明成全局变量可以减小开销
    18 inline void writeint(int i) {
    19   int p = 0;
    20   if(i == 0) p++; // 特殊情况:i等于0的时候需要输出0,而不是什么也不输出
    21   else while(i) {
    22     buf[p++] = i % 10;
    23     i /= 10;
    24   }
    25   for(int j = p-1; j >=0; j--) putchar('0' + buf[j]); // 逆序输出
    26 }
    27 
    28 int main() {
    29   int n, x, c[101];
    30   while(n = readint()) {
    31     memset(c, 0, sizeof(c));
    32     for(int i = 0; i < n; i++) c[readint()]++;
    33     int first = 1;
    34     for(int i = 1; i <= 100; i++)
    35       for(int j = 0; j < c[i]; j++) {
    36         if(!first) putchar(' ');
    37         first = 0;
    38         writeint(i);
    39       }
    40     putchar('
    ');
    41   }
    42   return 0;
    43 }
  • 相关阅读:
    GISer面对创业的困惑
    近期微博吐槽言论存档,涉及“性能优化”、C++陋习等
    HDU 2825 Wireless Password【AC自动机+DP】
    20130809, 微软八月安全补丁提前通知
    终于把3DMAX的MSE搞定了!
    UVA 11464 Even Parity (独特思路)
    [置顶] hdu 4418 高斯消元解方程求期望
    UVA 10652 Board Wrapping
    少儿编程-教育:少儿编程教育
    少儿编程:目录
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/3202744.html
Copyright © 2011-2022 走看看