[ACM学习心得]关于sync_with_stdio(false);
编程算法
在网上查看别人的ACM代码时,发现别人输入输出语句用的总是scanf与printf,有点不解,还以为他们用的都是C语言,而非C++,但今天做的一道题(Sort):
发现与网上的其他高手使用完全相同的方法,使用scanf及printf的代码提交后Accepted,而使用cin及cout的却Time Limit Exceeded,代码如下:
代码一(Accepted):
- #include<iostream>
- using namespace std;
- bool a[1000001];
- int main()
- {
- int n, m, num, count;
- while(scanf("%d%d",&n,&m)!=EOF){
- memset(a, 0, sizeof(a));
- for(int i=0; i<n; i++){
- scanf("%d",&num);
- a[num + 500000] = 1;
- }
- count = 0;
- for(int j = 1000000; j >= 0; --j){
- if(a[j]){
- if(count == m - 1){
- printf("%d\n",j-500000);
- break;
- }
- printf("%d ",j-500000);
- count++;
- }
- }
- }
- return 0;
- }
代码二(Time Limit Exceeded):
- #include<iostream>
- using namespace std;
- bool a[1000001];
- int main()
- {
- int n, m, num, count;
- while(cin >> n >> m){
- memset(a, 0, sizeof(a));
- for(int i=0; i<n; i++){
- cin >> num;
- a[num + 500000] = 1;
- }
- count = 0;
- for(int j = 1000000; j >= 0; --j){
- if(a[j]){
- if(count == m - 1){
- cout << j - 500000 << endl;
- break;
- }
- cout << j - 500000 << " ";
- count++;
- }
- }
- }
- return 0;
- }
可以看出,代码思路完全一样,只是输入输出方法不同,问过老师,加上这一句代码后使用cin及cout也可以Accepted:
- std::ios::sync_with_stdio(false);
百度了一下,原来而cin,cout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入输出缓存,可以节省许多时间,使效率与scanf与printf相差无几,还有应注意的是scanf与printf使用的头文件应是stdio.h而不是iostream。
如需转载请注明出处:杰拉斯的博客
当前暂无评论 »