您的位置:首页 > 其它

《算法竞赛-训练指南》第一章-1.17_UVa 11462

2013-07-20 09:04 281 查看
我就说,这本书上都是些经典的题目,怎么可能出那么简单的题目,应该是有他目的的。

果然,这道题目,用系统函数的sort能过,但是572ms,用我写的hash也能过476ms。

但是如果用书本上的解题技巧,那就是快速的过了,162ms。这差距的时间还是蛮大的!

数据量一般达到百万之后用这个快速的输入输出函数就非常的快了。不错,还是长见识了。

这道题目的代码到是没有什么意思,我把我的输入输入函数贴出来吧,可以解决正负数的问题。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

int hash[105];

int buf[10];

int readInt()
{
char c = getchar();
int flag = 0;
while (!isdigit(c))
{
if (c == '-')
{
flag = 1;
}
c = getchar();
}
int x = 0;
while (isdigit(c))
{
x = x * 10 + c - '0';
c = getchar();
}
if (flag == 0)
{
return x;
}
else
{
return -1 * x;
}
}

void writeInt(int x)
{
int p = 0;
int flag = 0;
if (x < 0)
{
flag = 1;
}
if (x == 0)
{
p++;
}
while (x)
{
buf[p++] = x % 10;
x /= 10;
}
if (flag == 0)
{
for (int i = p - 1; i >= 0; i--)
{
putchar('0' + buf[i]);
}
}
else
{
putschar('-');
for (int i = p - 1; i >= 0; i--)
{
putchar('0' + buf[i]);
}
}
}

int main()
{
int N;
while (N = readInt())
{
memset(hash, 0, sizeof(hash));
for (int i = 0; i < N; i++)
{
hash[readInt()]++;
}
int first = 1;
for (int i = 1; i <= 100; i++)
{
while (hash[i])
{
if (!first)
{
putchar(' ');
}
first = 0;
writeInt(i);
hash[i]--;
}
}
puts("");
}
// system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: