HDOJ 1425 : Sort

来源:互联网 发布:地图标识软件 编辑:程序博客网 时间:2024/06/05 11:16

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1425

该题目是一种简单的hash应用,关键是我在编程过程中遇到的问题。

#include <iostream>#include <memory>using namespace std;int hash_table[1000001] = {0};int main(){int temp;int m, n;while (cin>>n>>m){int max = -1;memset(hash_table, 0, sizeof(hash_table));for (int i=0; i<n; i++){scanf("%d", &temp);//cin>>temp;temp += 500000;hash_table[temp] = 1;if (temp > max){max = temp;}}int cnt = 0;for (int i=max; i>=0; --i){if (hash_table[i]){cnt++;if (cnt == m){printf("%d\n", i-500000);//cout<<i-500000<<endl;}else{printf("%d ", i-500000);//cout<<i-500000<<" ";}}if (cnt == m){break;}}}return 0;}

 问题:当我使用cin和cout时Time Limit Exceeded,而使用scanf和printf时就Accepted。

原因分析:经过查资料可以知道,cin和cout是在编译期间就决定读入类型,而scanf和printf是在运行期间才决定读入类型的,编译器无法优化,而且还要识别字符串。理论上cin比scanf要快,实际上cin比scanf要慢的原因是编译器对cin和cout处理过于保守。详细见http://hi.baidu.com/i5love1you9/item/2b97cb3dd91f20b7134b14c5。

I/O运行速度通常和它的功能多少成反比。

按照功能多少排序:cin/cout > scanf()/printf() > gets()/puts() > getchar()/putchar().

按照速度快慢排序:cin/cout < scanf()/printf() < gets()/puts() < getchar()/putchar().

原创粉丝点击