您的位置:首页 > 其它

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

2014-07-24 14:34 295 查看

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: