第一章例题17年龄排序学UVa11462(内存受限问题,计数排序)

11462 - Age Sort

Time limit: 5.000 seconds

B

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.


Problem Setter: Mohammad Mahmudur Rahman

Special Thanks: Shahriar Manzoor

 

 

/*由于输入文件大约有25M,而内存只有2M,因此我们甚至不能把所有的数据全部读入内存,
因此无法使用快速排序的方法(快排超不超时我就不知道了,n的上限为200万)。
但是输入的数据的范围是1到100之间的整数,范围很小,因此我们可以采用计数排序的方法
开一个101大小的数组,用data[x]存储x出现的次数,就很简单了啊*/

/*虽然到这里主要思想完事了,但是别忙着高兴,输出的格式控制是个小问题啊。
因为第一个数要直接输出,后面的其他数在输出之前要先输出一个空格。
用first=0标志还没有输出过整数,=1标志已经输出过整数了,用来控制空格
*/

#include<iostream>
#include<cstdio>
#include<cstring>/*用到了memset函数*/
using namespace std;
int data[101];/*计数排序数组,用来存储每个年龄的人各有多少个*/
int n,x;/*n为要输入的数据的个数,x为某一个要输入的数据值*/
int main()
{
 int i;
 while(cin>>n)
 {
  if(n==0){break;}
  memset(data,0,sizeof(data));
  for(i=0;i<n;i++)
  {
   scanf("%d",&x);
   data[x]++;/*data[x]里面存的是数据x出现的次数*/
  }
  int first=0;/*用first=0标志还没有输出过整数,=1标志已经输出过整数了,用来控制空格*/
  for(i=1;i<=100;i++)/*注意这里要写i<=100 ,不是i<=n,别犯傻*/
  {
   while(data[i]--)
   {
    if(first){printf(" ");}//如果已经输出过整数了,在输出数据之前要先处处空格
    printf("%d",i);/*这里输出的应该是i,不是data[i],data[i]是个数,别犯傻*/
    first=1;/*在有数据输出之后一定要及时把first设定为1,否则前面的空格输出会出问题*/
   }
  }
  printf("\n");
 }
 return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值